find the standard deviation of all values in a map in rust

To find the standard deviation of all the values in a HashMap in Rust, we can follow the steps below:

  1. Firstly, we will calculate the mean of all the values in the HashMap. We will iterate through all the values in the map and find the sum of all values. Then we will divide the sum by the total number of values to get the mean.
  2. Next, we will calculate the variance of all the values in the map. We will iterate through all the values in the map again and for each value, we will subtract it from the mean and square the result. We will then find the sum of all the squared differences and divide it by the total number of values.
  3. Finally, we can calculate the standard deviation by taking the square root of the variance.

Here's the implementation in Rust:

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

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

    // adding some values to the map
    values.insert("a", 10);
    values.insert("b", 20);
    values.insert("c", 30);

    let total = values.len();
    let mean = values.values().sum::<i32>() as f64 / total as f64;

    let variance = values.values()
                        .map(|val| {
                            let diff = (*val as f64 - mean).powi(2);
                            diff
                        })
                        .sum::<f64>() / total as f64;

    let standard_deviation = variance.sqrt();
    println!("Standard Deviation: {}", standard_deviation);
}
666 chars
24 lines

In this implementation, we first create a HashMap called values and add some values to it. Then we find the mean of all the values in the map by calculating the sum of all the values and dividing it by the total number of values.

We then calculate the variance by iterating through all the values in the map, subtracting each value from the mean and squaring the difference. We then find the sum of all the squared differences and divide it by the total number of values.

Finally, we calculate the standard deviation by taking the square root of the variance and print the result.

gistlibby LogSnag