find the mode of all keys in a map in rust

To find the mode of all keys in a Rust HashMap, we first need to count the number of occurrences of each key. We can do this by using an Iterator to iterate over the keys in the HashMap, keeping a count for each key.

main.rs
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("a", 1);
    map.insert("b", 2);
    map.insert("c", 2);
    map.insert("d", 3);

    // Count the occurrences of each key
    let mut counts = HashMap::new();
    for key in map.keys() {
        let count = counts.entry(key).or_insert(0);
        *count += 1;
    }

    // Find the key(s) with the maximum count
    let max_count = counts.values().max().unwrap();
    let modes: Vec<_> = counts
        .iter()
        .filter(|(_, &count)| count == *max_count)
        .map(|(&key, _)| key)
        .collect();

    println!("Mode(s): {:?}", modes);
}
648 chars
27 lines

In this example, we first create a HashMap with some keys and values. We then create another HashMap called counts to keep track of the number of occurrences of each key in the original HashMap.

We iterate over the keys using an Iterator and use the HashMap::entry method to insert a new key-value pair if the key does not already exist in counts. We then increment the count for that key by 1.

After all the counts have been calculated, we use the HashMap::values method to create an iterator over the count values. We find the maximum count using the Iterator::max method, and then filter the counts HashMap to find the key(s) with that maximum count.

Finally, we use Iterator::map to transform the resulting (&String, &i32) tuples into a Vec<String> containing just the keys with the maximum count. This Vec contains the mode(s) of the original HashMap keys.

gistlibby LogSnag