The Book chapter 08 exercise 1: Musings on Hashmaps

⚓ Rust    📅 2025-12-04    👤 surdeus    👁️ 1      

surdeus

Hi,

currently I am working through the Rust Programming Language book and am stuck in chapter 08 at exercise 1. I put the exercise text in the code comment below.

My question is: is my code as ugly as it feels to me (see: // ugly... comment)? I am certain that there are better solutions to this ... but are there better solutions if you only take the book up to chapter 08 into account? ... I am wondering what possible solution the author of the exercise had in mind.

Thanks for any hints. :slight_smile:

// Given a list of integers, use a vector and return the
// 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 std::collections::HashMap;

fn median(mut numbers: Vec<i32>) -> i32 {
    let index = numbers.len() / 2;
    numbers.sort();
    numbers[index]
}

fn mode(numbers: Vec<i32>) -> Option<i32> {
    if numbers.is_empty() {
        return None;
    }

    let mut map = HashMap::new();
    for n in numbers {
        let count = map.entry(n).or_insert(0);
        *count += 1;
    }

    // ugly ...
    let mut out = 0;
    let mut max = 0;
    for (k, v) in map {
        if v > max {
            max = v;
            out = k;
        }
    }
    Some(out)
}

fn main() {
    let numbers = vec![-1, 42, -10, 2, -23, 12, -3, 42, -5, 23, -8, 16, -42, 13];
    println!("Median: {}", median(numbers.clone()));
    println!("Mode: {}", mode(numbers).expect("Error"));
}

(Playground)

Output:

Median: 2
Mode: 42

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.03s
     Running `target/debug/playground`

4 posts - 3 participants

Read full topic

🏷️ Rust_feed