Hello everyone,
This is my first time writing Rust. I have been studying from the Official Rust Book without using any AI assistance. I spent almost 3 hours working on this specific exercise (Chapter 8: calculating median and mode) to get it to this point.
Even though it works, I am not sure if there is anything I am missing or if this is the idiomatic way to write Rust.
My questions are:
- Are there better or more idiomatic ways to implement this logic?
- Are there any edge cases or best practices that I overlooked?
use std::collections::HashMap;
fn main() {
let mut list_integer = vec![7, 24, 3, 24, 10];
let mut mode: HashMap<i32, i32> = HashMap::new();
let _sorted_list = &list_integer.sort_by(|a, b| a.cmp(b));
for &item in &list_integer{
mode.entry(item).and_modify(|counter| *counter += 1).or_insert(1);
}
let find_mode = mode.iter().max_by(|x, y| x.cmp(y)).unwrap();
let mode_again = find_mode.0;
let median_cal = &list_integer.iter().enumerate().len() / 2;
let median = &list_integer[median_cal];
println!("mode is : {mode_again}");
println!("median is : {median}");
}