find the mode of a list of numbers in rust

To find the mode of a list of numbers in Rust, we can use a simple algorithm where we iterate through the list and keep track of the count of each number in a hash map. Once we have counted all the numbers, we can iterate through the hash map and find the number with the highest count, which is the mode.

main.rs
use std::collections::HashMap;

fn main() {
    let numbers = vec![1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5];
    let mut count_map = HashMap::new();

    for &num in &numbers {
        let count = count_map.entry(num).or_insert(0);
        *count += 1;
    }

    let mut mode = 0;
    let mut mode_count = 0;

    for (&num, &count) in &count_map {
        if count > mode_count {
            mode = num;
            mode_count = count;
        }
    }

    println!("The mode is {}", mode);
}
490 chars
24 lines

In this code, we create a vector of numbers and a hash map to keep track of the count of each number. We then iterate through the vector and increment the count of each number in the hash map. Finally, we iterate through the hash map and find the number with the highest count, which is the mode.

gistlibby LogSnag