Skip to content

Instantly share code, notes, and snippets.

@TheCreatorAMA
Last active August 18, 2022 18:06
Show Gist options
  • Save TheCreatorAMA/b36f0c8cc14961a2ff54a15844a01093 to your computer and use it in GitHub Desktop.
Save TheCreatorAMA/b36f0c8cc14961a2ff54a15844a01093 to your computer and use it in GitHub Desktop.
Finding Mean, Median and Mode in Rust (chapter 8 exercise from rust-lang book)
use std::collections::HashMap;
fn main() {
let mut x: Vec<i32> = vec![6,3,2,2,5,7,9,9,8,6,4,10,11,11,11,11,12,13,14];
println!("Inputted vector: {:?}", x);
println!("Mean: {}", mean(&x));
println!("Median: {}", median(&mut x));
let y = mode(&x);
println!("Mode: value {} occurs {} times", y.0, y.1);
}
fn mean(vec: &Vec<i32>) -> f32 {
let len = vec.len() as f32;
let mut sum = 0;
for num in vec {
sum += num;
}
sum as f32 / len
}
fn median(vec: &mut Vec<i32>) -> f32 {
vec.sort();
let mid = vec.len() / 2;
if vec.len() % 2 == 0 {
(vec[mid - 1] + vec[mid]) as f32/ 2.0
} else {
vec[mid] as f32
}
}
fn mode(vec: &Vec<i32>) -> (i32, i32) {
let mut map = HashMap::new();
for number in vec {
let count = map.entry(number).or_insert(0);
*count += 1;
}
let mut max_key: i32 = 0;
let mut max_val: i32 = 0;
for (k, v) in map {
if v > max_val {
max_val = v;
max_key = *k;
}
}
(max_key, max_val)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment