find the average of all keys in a map in rust

One way to find the average of all keys in a map in Rust would be to first iterate through the map, calculating the sum of all keys, and then divide the sum by the length of the map.

Here is some sample code that demonstrates how to do this:

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

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

    let sum: usize = map.keys().map(|k| k.len()).sum();
    let avg = sum as f32 / map.len() as f32;

    println!("Average key length: {}", avg); // prints: Average key length: 1.0
}
335 chars
14 lines

In this example, we create a new HashMap, insert some key-value pairs, then calculate the sum of the length of each key using the keys() method and the map() iterator. We convert the sum to a f32 and divide it by the length of the map, which we also convert to a f32. Finally, we print the result, which in this case is 1.0.

related categories

gistlibby LogSnag