Hi All,
My friend and I are learning rust after many years commercial experience in other languages. Loving it so far! We're comparing notes, but I'd like to get some feedback from the community too.
This is my code to the exercise at the end of chapter 8 of the 'book' here
It feels a reasonably elegant solution although far from 'perfect', but I see that Rust has slightly different techniques to other languages that I might not have picked up yet.
Please can you comment if you'd have done this in a different way? Any ways to improve performance, or any techniques you'd suggest I take a look at?
fn main() {
let mut lst = vec![
78, 55, 56, 99, 23, 55, 56, 55, 23, 9, 99, 1, 1, 1, 99, 66, 88,
];
lst.sort();
let total: i32 = lst.iter().sum();
let modes = get_mode(&lst);
let joined: String = modes.1.iter().map(|&x| x.to_string() + ",").collect();
print!(
"
Len: \t{} items
Total: \t{}
Mean: \t{}
Median:\t{}
Modes with {} occurances: {}",
lst.len(),
total,
mean(&total, &lst),
median(&lst),
modes.0,
joined
);
}
// calculate the mean average
fn mean(total: &i32, lst: &Vec<i32>) -> i32 {
total / (lst.len() as i32)
}
// get the median average
fn median(lst: &Vec<i32>) -> i32 {
lst[lst.len() / 2]
}
// get the mode average
fn get_mode(lst: &Vec<i32>) -> (i32, Vec<i32>) {
let mut scores = HashMap::new();
// Use a hashmap to count occurances of each score
for num in lst.iter() {
let e = scores.entry(num).or_insert(0 as i32);
*e += 1;
}
// Get the highest number of occurances
let max_occurances = match scores.values().max() {
Some(i) => i,
None => &0,
};
// get all keys that have the value equal to max occruances, these are all matches for the mode average
let m =
scores
.iter()
.filter(|(&_key, &val)| val == *max_occurances)
.map(|(&k, &_v)| *k).collect();
(*max_occurances, m)
}