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
}
``
```