Created
November 10, 2023 00:23
-
-
Save jerry-maheswara-github/7506b3589daf03a8d99198d3dbfb5151 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// #![allow(unused)] | |
use std::collections::btree_map::BTreeMap; | |
use std::collections::HashMap; | |
use std::iter::Iterator; | |
use std::time::Instant; | |
fn main() { | |
let start = Instant::now(); | |
let message = " | |
i love rust love ya | |
" | |
; | |
let cc : HashMap<String, i32> = _hitung_huruf(message); | |
// let cc : HashMap<String, i32> = _hitung_kata(message); | |
let mut sorted_data: Vec<_> = cc.iter().collect(); | |
sorted_data.sort_by(|a, b| b.1.cmp(&a.1)); // desc | |
// sorted_data.sort_by(|a, b| a.1.cmp(b.1)); // asc | |
println!("{:?}", sorted_data); | |
println!("Number of occurrences of each character: {}", cc.len()); | |
// for (key, value) in sorted_data { | |
// // println!("{}: {}", key, value); | |
// } | |
// println!("Number of occurrences of each word:"); | |
// println!("{:#?}", _hitung_kata(message)); | |
let end = Instant::now(); | |
let duration = end.duration_since(start); | |
let _nanoseconds = duration.subsec_nanos(); | |
println!("benchmark: {:?}", duration); | |
} | |
fn _hitung_huruf(message:&str) -> HashMap<String, i32> { | |
let mut count = BTreeMap::new(); | |
let mut result: HashMap<String, i32> = HashMap::new(); | |
for c in message.chars().filter(|s| {!s.is_whitespace()}) { | |
*count.entry(c).or_insert(0) += 1; | |
} | |
for (char, count) in &count { | |
result.insert({char}.to_string(), *count); | |
} | |
return result; | |
} | |
fn _hitung_kata(message:&str) -> HashMap<String, i32> { | |
let mut count = BTreeMap::new(); | |
let mut result: HashMap<String, i32> = HashMap::new(); | |
let words = message | |
.split(|c: char| {!(c.is_alphabetic() || c == '\'')}) | |
.filter(|s| !s.is_empty()); | |
for c in words { | |
*(count.entry(c.to_string()).or_insert(0)) += 1; | |
} | |
for (char, count) in &count { | |
result.insert({char}.to_string(), *count); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment