I am reading the Rust book. I am on chapter 8; this is the assignment:
Given a list of integers, use a vector and return the median (when sorted, the value in the middle position) and mode (the value that occurs most often; a hash map will be helpful here) of the list.
And here is my code for it:
`
#![allow(unused)]
use std::collections::HashMap;
fn main() {
let mut integers = vec![
4, 9, 6, 7, 3, 4, 5, 6, 2, 13, 9, 5, 2, 3, 6, 8, 4, 5, 5, 6, 9, 8, 6,
];
// arrange numbers in ascending order
integers.sort_by(|a, b| a.cmp(b));
let int_length = integers.len();
// check if the length of the numbers it is odd or even
if let 0 = int_length % 2 {
// for even
let mut answer = 0;
answer = int_length / 2;
let median = (integers[answer] + integers[answer + 1]) / 2;
println!("the median is {}", median)
} else {
//for odd
let mut answer = 0;
answer = int_length / 2 + 0.5 as usize;
let median = integers[answer];
println!("the median is {}", median)
}
let mut values_in_hashmap = HashMap::new();
// record the value of each occurence of the numbers in hashmap
for values in integers {
let count = values_in_hashmap.entry(values).or_insert(0);
*count += 1;
}
let mut current_highest_value = 0;
let mut modes = vec![];
// loop through the hashmap to get the highest value in the hashmap
for (key, value) in &values_in_hashmap {
if value > ¤t_highest_value {
current_highest_value = *value;
}
}
// push all the number with same value as the highest value to an array
for (key, value) in &values_in_hashmap {
if *value == current_highest_value {
modes.push(key)
}
}
println!(" the modes {:?}", modes);
}
`