Solutions to the exercises in the official Rust book [Chapter 8]


#1

Hello,

I arrived at Chapter 8 of the official Rust book and at the end there are some exercises. Is there any official (or at least good and well documented) solution out there ? I’ve tried searching the internets with no success, so I’m asking here!

I’d like to compare proper solutions to my crappy beginner solution to learn more.

Thanks in advance.


#2

There aren’t any official answers to the exercises that I know of, you can post them on this forum and request feedback for it, it’s what I did :slight_smile:


#3

That’s correct! Maybe after the book is finished, I can put up solutions :slight_smile:


#4

Ok so here we go. The exercise I did so far :

Given a list of integers, use a vector and return the mean (average), 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.

I’m open to all sorts of comment :

  • whether there’s a better way,
  • whether there’s a faster way,
  • memory/ownership management
  • code safety
  • whether it’s idiomatic or not
  • code style/formatting
  • etc.

Please remember that I haven’t finished the book yet, I’m stil at chapter 8. So I refrained myself from using features explained after like lambdas, function level comment/doc-string and all the things I don’t even know yet.

Also, while I’m “happy” with my solutions for the mean and median (they handle empty vectors and NaN somehow), the code for mode is… beginner-level crap haha.

Thanks in advance for all your comments!

fn exercise1() {
    let int_list: Vec<i32> = vec![1, 2, 3, 3, 4, 5, 5, 5, 6, 7, 51];

    match mean(&int_list) {
        Some(avg) => println!("mean {}", avg),
        None => println!("mean unavailable for {:?}", int_list),
    }
    match median((&int_list)) {
        Some(result) => { println!("median {}", result)},
        None => { println!("median unavailable for {:?}", int_list);}
    }

    println!("mode {}", mode(&int_list));
}

fn mean(int_list: &Vec<i32>) -> Option<f64> {
    let sum: i32 = int_list.iter().sum();
    let maybe_mean = sum as f64 / int_list.len() as f64;

    if maybe_mean.is_nan() {
        None
    } else {
        Some(maybe_mean)
    }
}

fn median(int_list: &Vec<i32>) -> Option<i32> {
    let mut new_list = int_list.clone();
    new_list.sort();

    match (new_list.first(), new_list.last()) {
        (Some(first), Some(last)) => Some((first + last) / 2),
        (_, _) => None,
    }
}

fn mode(int_list: &Vec<i32>) -> i32 {
    let mut occurrences = HashMap::new();

    for v in int_list.iter() {
        let mut count = occurrences.entry(v).or_insert(0);
        *count += 1;
    }

    let mut maximum = occurrences.get(&int_list[0]).expect("No value in occurrences for first value of int_list");
    let mut result = &int_list[0];

    for (key, value) in &occurrences {
        if value > maximum {
            result = *key;
            maximum = value;
        }
    }

    *result
}
``