Skip to content

Instantly share code, notes, and snippets.

@2color
Created January 4, 2022 14:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 2color/1c305621ed1672550d136547a4b5f6d4 to your computer and use it in GitHub Desktop.
Save 2color/1c305621ed1672550d136547a4b5f6d4 to your computer and use it in GitHub Desktop.
Mean, median, and mode of a vector with Rust
use std::collections::HashMap;
fn main() {
let v: Vec<u32> = vec![10, 20, 20, 30, 38, 42, 48, 51, 62, 70];
println!("vector: {:?}", v);
println!("mean: {}", mean(&v));
// println!("median: {}", median(&mut v));
println!("median: {}", median_1(&v));
// println!("median: {}", median_2(v.clone()));
println!("mode: {}", mode(&v));
}
fn mean(v: &[u32]) -> u32 {
let mut mean: u32 = 0;
for i in v {
mean += i;
}
mean / v.len() as u32
}
// borrows an immutable reference to v
// Slighly inefficient because it has to clone vector
// called with println!("median: {}", median(&v));
fn median_1(v: &Vec<u32>) -> u32 {
let mut sorted = v.clone();
sorted.sort();
let median_key = (sorted.len() - 1) / 2;
let median = sorted.get(median_key).expect("invalid key");
*median
}
// This will move ownership of v to the function scope
// Slighly inefficient because it has to clone vector
// But the downside is that it becomes messy to return ownership of `v`
// so that the caller can continue using `v`
fn median_2(mut v: Vec<u32>) -> u32 {
v.sort();
let median_key = (v.len() - 1) / 2;
let median = v.get(median_key).expect("invalid key");
*median
}
// borrows an immutable reference to v and requires v to be mutable
// called with println!("median: {}", median(&mut v));
fn median(v: &mut [u32]) -> u32 {
v.sort();
let median_key = (v.len() - 1) / 2;
let median = v.get(median_key).expect("invalid key");
*median
}
fn mode(v: &[u32]) -> u32 {
let mut modes = HashMap::new();
for i in v {
let count = modes.entry(*i).or_insert(0 as u32);
*count += 1;
}
let mut max_count: u32 = 0;
let mut max_val: u32 = 0;
for (v, count) in modes.iter() {
if count > &max_count {
max_count = *count;
max_val = *v;
}
}
max_val
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment