So I'm currently making my way through the Rust book, and I ran into an interesting problem asking me to write code to calculate the mode. I came up with an answer, but I was wondering if there was a way to do the same thing with more higher order functions. I'm using 2 for loops currently, doesn't really look that efficient
use std::collections::HashMap;
fn main() {
let number_vec = vec![19, 54, 88, 42, 16, 72, 63, 77, 90, 45, 45, 90, 75, 19];
let mut mode_hashmap = HashMap::new();
for i in number_vec {
*mode_hashmap.entry(i).or_insert(0) += 1;
}
let mut mode_vec = Vec::new();
let mut max_occurrences = 0;
for (key, value) in mode_hashmap {
if value > max_occurrences {
max_occurrences = value;
mode_vec.clear();
mode_vec.push(key);
}
else if value == max_occurrences {
mode_vec.push(key);
}
}
mode_vec.sort_unstable();
println!("{:?}", mode_vec);
}