Skip to content

Instantly share code, notes, and snippets.

@dannyrevenant
Created March 11, 2019 17:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dannyrevenant/43862de666091074a3cad76c21cc23fe to your computer and use it in GitHub Desktop.
Save dannyrevenant/43862de666091074a3cad76c21cc23fe to your computer and use it in GitHub Desktop.
Rust Test: Given a list of integers, use a vector and return the: mean median and mode of the list.
// Given a list of integers, use a vector and return the:
// mean (the average value)
// 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 rand::{
thread_rng,
Rng,
};
use std::collections::HashMap;
fn main() {
// our vector of random numbers to work with
let mut numbers: Vec<u32> = Vec::new();
// work out how many random numbers to use ( 1 - 10 )
let mut rng = thread_rng();
let mut total_items: u32 = rng.gen_range(1, 10);
println!("Total Items: {}", total_items);
// generate that number of items
while total_items > 0 {
numbers.push(rng.gen_range(1, 10));
total_items -= 1;
}
// sort the numbers
numbers.sort();
println!("Numbers: {:#?}", numbers);
// sum the numbers
let mut total: u32 = 0;
for i in numbers.iter() {
total += i;
}
println!("Total: {}", total);
// 1. Mean
let mean: f32 = total as f32 / numbers.len() as f32;
println!("Mean: {}", mean);
// 2. Median
let median = numbers[ numbers.len() / 2 ];
println!("Median: {}", median);
// 3. Mode
let mut occurrences = HashMap::new();
// insert to hashmap
for i in numbers.iter() {
let count = occurrences.entry(i).or_insert(0);
*count += 1;
}
// iterate the occurances, returning the one with the most repetitions
let mode = occurrences
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(val, _)| val)
.expect("Cannot compute the mode of zero numbers");
println!("Mode: {}", mode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment