Last active
September 13, 2019 22:10
-
-
Save graciano/cb109d499fb4d67f87b645c83d2921d2 to your computer and use it in GitHub Desktop.
rust book exercise
This file contains hidden or 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; | |
fn mean(arr: &Vec<usize>) -> usize { | |
let sum = arr.iter().fold(0, |sum, el| sum + el); | |
sum / arr.len() | |
} | |
fn median(arr: &Vec<usize>) -> usize { | |
let half_position = arr.len() / 2; | |
let mut input_sorted = arr.clone(); | |
input_sorted.sort(); // this mutates the vec | |
input_sorted[half_position] | |
} | |
fn mode(arr: &Vec<usize>) -> usize { | |
let mut freq_map = HashMap::new(); | |
for &num in arr { | |
*freq_map.entry(num).or_insert(0) += 1; | |
} | |
let mut sorted_freq: Vec<(&usize, &usize)> = freq_map.iter().collect(); | |
sorted_freq.sort_by(|(_, a), (_, &b)| b.cmp(a)); | |
*sorted_freq[0].0 | |
} | |
fn main() { | |
let input_numbers = vec![15, 20, 110, 5, 0, 2055, 11, 11, 11, 11 ,12, 2, 2, 23, 32, 23, 23, 2]; | |
println!("mean: {}", mean(&input_numbers)); | |
println!("median: {}", median(&input_numbers)); | |
println!("mode: {}", mode(&input_numbers)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment