Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created February 16, 2019 15:25
Show Gist options
  • Save rust-play/1e3ac1c0b5cf6a803bbba9346012fbf6 to your computer and use it in GitHub Desktop.
Save rust-play/1e3ac1c0b5cf6a803bbba9346012fbf6 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
#![allow(unused)]
use std::collections::HashMap;
fn main() {
let mut vec = vec![3, 5, 6, 3, 4, 7, 4];
println!("Averege ={}", averege(&vec));
assert_eq!(median(&mut vec), 4.0);
println!("Median ={}", median(&mut vec));
println!("Mode ={}", mode(&vec));
}
fn averege(v: &[i32]) -> f32 {
v.iter().sum::<i32>() as f32 / v.len() as f32
}
fn median(v: &mut Vec<i32>) -> f32 {
v.sort();
let size = v.len();
if size % 2 == 0 {
(v[size / 2] + v[size / 2 - 1]) as f32 / 2.0
} else {
v[size / 2] as f32
}
}
fn mode(v: &[i32]) -> i32 {
let mut occurrences = HashMap::new();
for &value in v {
*occurrences.entry(value).or_insert(0) += 1;
}
occurrences
.into_iter()
.max_by_key(|&(_, count)| count)
.map(|(val, _)| val)
.expect("Can not compute the mode of zero number")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment