Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * 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.
- */
- use std::collections::HashMap;
- fn main() {
- let list = vec![1, 5, 7, 8, 12, 9, 32, 6, 9, 10, 10, 10];
- fn median(vector: &Vec<u32>) -> u32 {
- let mut auxiliary_vector = vector.clone();
- auxiliary_vector.sort();
- auxiliary_vector[auxiliary_vector.len() / 2]
- }
- fn mode(vector: &Vec<u32>) -> u32 {
- let mut map = HashMap::new();
- for number in vector {
- let times = map.entry(number).or_insert(0);
- *times += 1;
- }
- let mut max_times = 0;
- let mut max_times_number = 0;
- for (number, times) in map {
- if times > max_times {
- max_times = times;
- max_times_number = *number;
- }
- }
- max_times_number
- }
- println!("Median of {:?} is {}", list, median(&list));
- println!("Mode of {:?} is {}", list, mode(&list));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement