find the average of all values in a map in rust

Here's how to find the average of all values in a HashMap in Rust:

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

fn main() {
    let mut map = HashMap::new();

    // insert some values into the map
    map.insert("a", 1);
    map.insert("b", 2);
    map.insert("c", 3);
    map.insert("d", 4);

    // calculate the average of the values in the map
    let sum: i32 = map.values().sum(); // sum all the values in the map
    let count = map.len(); // get the number of values in the map
    let average = sum / count as i32; // divide the sum by the count as a float
    println!("average: {}", average);
}
527 chars
18 lines

This code first creates a HashMap with some initial values. Then it calculates the sum of all values using the values() method of the HashMap, which returns an iterator of all values in the map. The sum() method from the standard library is called on this iterator to calculate the total sum of all values. The number of values in the map is then obtained using the len() method, and the average is simply the sum divided by the number of values in the map. The result is printed to the console.

related categories

gistlibby LogSnag