Skip to content

Instantly share code, notes, and snippets.

@konsumer
Last active July 14, 2022 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save konsumer/74b4e25bd3034b7e489499cbf863bb2d to your computer and use it in GitHub Desktop.
Save konsumer/74b4e25bd3034b7e489499cbf863bb2d to your computer and use it in GitHub Desktop.
learning rust
#[derive(Debug)]
struct VecStats {
mean: f32,
median: i32,
mode: i32
}
impl VecStats {
fn new(numbers: &Vec<i32>) -> VecStats {
VecStats {
mean: numbers.iter().sum::<i32>() as f32 / numbers.len() as f32,
median: {
let mut vec = numbers.clone();
vec.sort();
vec[ vec.len() / 2 ]
},
mode: {
let mut map = HashMap::new();
let mut current_high_count = i32::MIN;
let mut current_high_val = 0;
for n in numbers {
let count = map.entry(n).or_insert(0);
*count += 1;
if count > &mut current_high_count {
current_high_count = *count;
current_high_val = n.clone();
}
}
current_high_val
}
}
}
}
fn main() {
let numbers = vec![5, 6, 7, 3, 4, 9, 6, 7, 7];
println!("{:?}", VecStats::new(&numbers));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment