Created
July 29, 2020 20:00
-
-
Save peaceman/1af00dc9c9e7f7789c70cf1272c60330 to your computer and use it in GitHub Desktop.
rust lang book practice collections
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
use std::collections::HashMap; | |
use std::cmp::Ordering; | |
fn gen_mean(input: &Vec<u32>) -> String { | |
let sum = input.iter().fold(0, |acc, x| acc + x); | |
return (sum as usize / input.len()).to_string(); | |
} | |
fn gen_median(input: &Vec<u32>) -> String { | |
let is_odd = input.len() % 2 == 1; | |
let mut input = input.to_vec(); | |
input.sort_unstable(); | |
let input_len = input.len(); | |
let input_len_half = input_len / 2; | |
match is_odd { | |
true => { | |
input[input_len_half + 1].to_string() | |
}, | |
false => { | |
((input[input_len_half] + input[input_len_half + 1]) / 2) | |
.to_string() | |
}, | |
} | |
} | |
fn gen_middle(input: &Vec<u32>) -> String { | |
input[input.len() / 2 as usize].to_string() | |
} | |
fn gen_mode(input: &Vec<u32>) -> String { | |
let mut occurrences = HashMap::<u32, u32>::new(); | |
for &x in input.iter() { | |
let counter = occurrences.entry(x).or_insert(0); | |
*counter += 1; | |
} | |
let mut sorted: Vec<(&u32, &u32)> = occurrences.iter().collect(); | |
sorted.sort_by(|x, y| y.1.cmp(&x.1)); | |
sorted[0].0.to_string() | |
} | |
fn main() { | |
let input = vec!(4, 8, 15, 16, 23, 42, 16, 23, 23); | |
println!("{}", 11 as f32 / 2 as f32); | |
println!( | |
"mean: {}\nmedian: {}\nmiddle: {}\nmode: {}", | |
gen_mean(&input), | |
gen_median(&input), | |
gen_middle(&input), | |
gen_mode(&input) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment