Created
September 15, 2022 23:36
-
-
Save 0ex-d/4fe7c6c389ad95a5d7f753f724e1a198 to your computer and use it in GitHub Desktop.
Get a list of data and count the number of repeating groups and display the most frequent
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
use std::collections::{BTreeMap, HashMap}; | |
fn main() { | |
let frequency = [19, 19, 20, 32, 35, 19, 32]; | |
// use hashmap to store k/v pairs | |
let mut seek_hash: HashMap<i32, u8> = HashMap::new(); | |
let mut seek_hash_sorted: BTreeMap<i32, u8> = BTreeMap::new(); | |
let mut highest_freq_val = 0; | |
let mut highest_freq_key = 0; | |
for num in frequency { | |
// check if key in hash map | |
match seek_hash.contains_key(&num) { | |
false => { | |
if num > 0 { | |
seek_hash.insert(num, 1); | |
} | |
} | |
true => { | |
// update existing value by hash key | |
*seek_hash.entry(num).or_default() += 1; | |
} | |
} | |
} | |
// insert into Btree map | |
// borrow (immut) from previous owner | |
let updated_hashmap = &seek_hash; | |
for (key, value) in updated_hashmap { | |
if value > &highest_freq_val { | |
highest_freq_val = *value; | |
highest_freq_key = *key; | |
} | |
// use a * to dereference the borrow | |
seek_hash_sorted.insert(*key, *value); | |
} | |
println!( | |
"most occurring number is: {} with {} occurrences", | |
highest_freq_key, highest_freq_val | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment