Skip to content

Instantly share code, notes, and snippets.

@dpurrington
Last active September 9, 2022 14:44
Show Gist options
  • Save dpurrington/bdbd3b8797eb9741a6b62647e8a775ea to your computer and use it in GitHub Desktop.
Save dpurrington/bdbd3b8797eb9741a6b62647e8a775ea to your computer and use it in GitHub Desktop.
use std::collections::HashMap;
#[derive(Debug)]
pub struct Stats {
pub average: f32,
pub min: i32,
pub max: i32,
pub mode: i32,
pub median: f32
}
pub fn get_stats(ints: &[i32]) -> Stats {
/// Takes a vector of integers and returns a Stats
/// structure with various statistical values
let mut sorted = ints.to_owned();
// median requires sorting, so we may as well deal with a sorted vector
sorted.sort_unstable();
let mut max = i32::MIN;
let mut min = i32::MAX;
// initially I had the following statements in a single line, but it was not very readable
// also, it took me a while to sort out what I needed to do in order to get the types to agree
let sum: i32 = sorted.iter().sum();
let average = sum as f32 / sorted.len() as f32;
// this variable will be used to determine the mode
let mut counts: HashMap<i32, i32> = HashMap::new();
for (_, v) in sorted.iter().enumerate() {
if max < *v { max = *v; }
if min > *v { min = *v; }
// running counter of each value
*counts.entry(*v)
.or_insert(0) += 1;
}
// compute the mode -- Marcus helped me with this one (especially map, copied, and expect)
let mode = counts.iter()
.max_by_key(|kv | kv.1)
.map(|kv| kv.0)
.copied()
.expect("there should be at least one value");
let length = sorted.len();
let median: f32 = match length % 2 {
0 => {
// this section is complicated because the median when there is an even number of elements
// is the average of the middle two
let mid_left = sorted[(length-1)/2];
let mid_right = sorted[length/2];
let sum = mid_left + mid_right;
sum as f32/2.0
},
_ => sorted[length/2] as f32
};
Stats { average, max, min, mode, median }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment