Last active
March 3, 2021 04:13
-
-
Save rosalogia/efbcaded3ed3dfdfc3fb64d988e95188 to your computer and use it in GitHub Desktop.
Mean, Median and Mode of a Vec<i32> in Rust
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use std::collections::HashMap; | |
| pub fn mean(values: &[i32]) -> f64 { | |
| let mut sum = 0.0; | |
| for x in values { | |
| sum += *x as f64; | |
| } | |
| sum / values.len() as f64 | |
| } | |
| pub fn median(values: &[i32]) -> f64 { | |
| let mut vc = values.to_vec(); | |
| vc.sort(); | |
| let length = vc.len(); | |
| if length % 2 == 0 { | |
| (vc[length / 2 - 1] + vc[length / 2]) as f64 / 2.0 | |
| } else { | |
| vc[length / 2] as f64 | |
| } | |
| } | |
| pub fn mode(values: &[i32]) -> i32 { | |
| let mut frequency_map: HashMap<i32, i32> = HashMap::new(); | |
| for x in values { | |
| let current = frequency_map.entry(*x).or_insert(0); | |
| *current += 1; | |
| } | |
| let (mut max_val, mut max_freq) = (-1, -1); | |
| for (val, freq) in frequency_map { | |
| if freq > max_freq { | |
| max_val = val; | |
| max_freq = freq; | |
| } | |
| } | |
| max_val | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment