How to calculates the frequency of odd and even numbers in the given matrix with Rust

1 Answer

0 votes
/*
    Function: countOddEven
    Purpose:  Counts how many odd and even numbers exist in the matrix.
    Parameters:
        - matrix: the 2D vector
        - rows:   number of rows in the matrix   (computed inside the function)
        - cols:   number of columns in the matrix (computed inside the function)
        - odd:    variable to store odd count
        - even:   variable to store even count
*/
fn count_odd_even(matrix: &Vec<Vec<i32>>) -> (i32, i32) {

    // Automatically compute matrix dimensions inside the function
    let rows: usize = matrix.len();
    let cols: usize = matrix[0].len();

    let mut odd: i32 = 0;
    let mut even: i32 = 0;

    for i in 0..rows {
        for j in 0..cols {

            // Check if the number is even or odd
            if matrix[i][j] % 2 == 0 {
                even += 1;
            } else {
                odd += 1;
            }
        }
    }

    (odd, even)
}

fn main() {

    let matrix: Vec<Vec<i32>> = vec![
        vec![1, 0, 2, 5],
        vec![3, 5, 6, 9],
        vec![7, 4, 1, 8],
    ];

    // Call the function (rows and cols are now computed inside)
    let (odd_count, even_count) = count_odd_even(&matrix);

    // Display the result
    println!("The frequency of odd numbers = {}", odd_count);
    println!("The frequency of even numbers = {}", even_count);
}


/*
run:

The frequency of odd numbers = 7
The frequency of even numbers = 5

*/

 



answered 3 days ago by avibootz

Related questions

...