Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code shared from the Rust Playground
use std::collections::HashMap;
#[derive(Debug)]
pub struct NumberData {
mean: f64,
median: i32,
mode: i32,
}
pub fn mean_median_mode(mut numbers: Vec<i32>) -> NumberData {
numbers.sort();
let mut sum: i32 = 0;
let l = numbers.len();
let mut middle = l / 2;
if l % 2 == 0 {
middle -= 1;
};
let mut occ = HashMap::new();
let mut max_mode: i32 = 0;
let mut mode_key: Option<i32> = None;
for num in numbers.clone() {
let count = occ.entry(num).or_insert(0);
*count += 1;
sum += num;
if *count > max_mode {
max_mode = *count;
mode_key = Some(num);
}
}
let median: i32 = numbers[middle];
return NumberData {
mean: sum as f64 / l as f64,
median,
mode: match mode_key {
Some(x) => x,
None => 0,
},
};
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
use super::*;
let testvec = vec![0, 1, 2, 3, 4];
let test_result = mean_median_mode(testvec);
assert_eq!(test_result.mean, 2.0);
assert_eq!(test_result.median, 2);
assert_eq!(test_result.mode, 0);
}
#[test]
fn it_also_works() {
use super::*;
let testvec = vec![187, -29, 3, 3, 3, -29, -39, -4];
let test_result = mean_median_mode(testvec);
assert_eq!(test_result.mean, 11.875);
assert_eq!(test_result.median, -4);
assert_eq!(test_result.mode, 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment