Skip to content

Instantly share code, notes, and snippets.

@gistub
Last active July 24, 2022 02:10
Show Gist options
  • Select an option

  • Save gistub/3a09c2ca6d2aeaa45bf50dc701ad0e9c to your computer and use it in GitHub Desktop.

Select an option

Save gistub/3a09c2ca6d2aeaa45bf50dc701ad0e9c to your computer and use it in GitHub Desktop.
[Rust: Book exercises]
#![allow(unused_variables)]
fn main() {
let mut v1 = vec![1, -5, 10, 3, 1, 0];
let mut v2 = vec![31, 5, 10, 3, 1, -83, -83, -83, 9, 10, 8];
let mut v3 = vec![5, 31, 5, 180, 3, 1, -83, 9, 10, 8];
println!("mean of v1: {}", mean(&v1));
println!("median of none: {:?}", median(&mut Vec::new()));
println!("median of v1: {:?}", median(&mut v1));
println!("median of v2: {:?}", median(&mut v2));
println!("median of v3: {:?}", median(&mut v3));
println!("mode of none: {:?}", mode(&Vec::new()));
println!("mode of v1: {:?}", mode(&v1));
println!("mode of v2: {:?}", mode(&v2));
println!("mode of v3: {:?}", mode(&v3));
let x: i32 = Vec::new().iter().sum();
println!("mode of v3: {:?}", x);
}
fn mode(v: &Vec<isize>) -> Option<isize> {
use std::collections::HashMap;
let mut m = HashMap::new();
v.iter().map(|i| *m.entry(*i).or_insert(0usize) += 1).count();
if let Some(x) = m.iter().max_by_key(|&(k, v)| v) {
Some(*x.0)
} else {
None
}
}
fn mean(v: &Vec<isize>) -> f64 {
match v.len() {
0 => 0f64,
n => v.iter().sum::<isize>() as f64 / n as f64,
}
}
fn median(v: &mut Vec<isize>) -> Option<isize> {
v.as_mut_slice().sort();
match v.len() {
0 => None,
n => Some(v[n / 2]),
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment