Last active
July 14, 2022 18:13
-
-
Save konsumer/74b4e25bd3034b7e489499cbf863bb2d to your computer and use it in GitHub Desktop.
learning rust
This file contains 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
#[derive(Debug)] | |
struct VecStats { | |
mean: f32, | |
median: i32, | |
mode: i32 | |
} | |
impl VecStats { | |
fn new(numbers: &Vec<i32>) -> VecStats { | |
VecStats { | |
mean: numbers.iter().sum::<i32>() as f32 / numbers.len() as f32, | |
median: { | |
let mut vec = numbers.clone(); | |
vec.sort(); | |
vec[ vec.len() / 2 ] | |
}, | |
mode: { | |
let mut map = HashMap::new(); | |
let mut current_high_count = i32::MIN; | |
let mut current_high_val = 0; | |
for n in numbers { | |
let count = map.entry(n).or_insert(0); | |
*count += 1; | |
if count > &mut current_high_count { | |
current_high_count = *count; | |
current_high_val = n.clone(); | |
} | |
} | |
current_high_val | |
} | |
} | |
} | |
} | |
fn main() { | |
let numbers = vec![5, 6, 7, 3, 4, 9, 6, 7, 7]; | |
println!("{:?}", VecStats::new(&numbers)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment