find the mode of all elements in an array in rust

To find the mode of all elements in an array in Rust, we can use a counting algorithm. First, we sort the array to make it easier to count the occurrences of each element. Then, we iterate through the sorted array, keeping track of the current element and its count. We also keep track of the element with the maximum count so far.

Here's the Rust code to implement this algorithm:

main.rs
fn mode(array: &[i32]) -> Option<i32> {
    if array.is_empty() {
        return None;
    }

    // Sort the array to make it easier to count the occurrences of each element.
    let mut sorted_array = array.to_vec();
    sorted_array.sort();

    let mut current_element = sorted_array[0];
    let mut current_count = 1;
    let mut max_element = current_element;
    let mut max_count = current_count;

    for &element in &sorted_array[1..] {
        if element == current_element {
            // We've found another occurrence of the current element.
            current_count += 1;
        } else {
            // We've found a new element. Update the max element if necessary.
            if current_count > max_count {
                max_element = current_element;
                max_count = current_count;
            }

            // Reset the current element and count.
            current_element = element;
            current_count = 1;
        }
    }

    // Check if the last element is the mode.
    if current_count > max_count {
        max_element = current_element;
        max_count = current_count;
    }

    Some(max_element)
}
1158 chars
40 lines

Here's an example usage of the mode function:

main.rs
let array = [1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 7, 7, 7];
assert_eq!(mode(&array), Some(7));
88 chars
3 lines

gistlibby LogSnag