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

1 Answer

0 votes
/*
    Function: countOddEven
    Purpose:  Counts how many odd and even numbers exist in the matrix.
    Parameters:
        - matrix: the 2D array
        - 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
*/
function countOddEven(matrix: number[][]): [number, number] {

    // Automatically compute matrix dimensions inside the function
    const rows: number = matrix.length;
    const cols: number = matrix[0].length;

    let odd: number = 0;
    let even: number = 0;

    for (let i: number = 0; i < rows; i++) {
        for (let j: number = 0; j < cols; j++) {

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

    return [odd, even];
}

function main(): void {

    const matrix: number[][] = [
        [1, 0, 2, 5],
        [3, 5, 6, 9],
        [7, 4, 1, 8]
    ];

    // Call the function (rows and cols are now computed inside)
    const result: [number, number] = countOddEven(matrix);
    const oddCount: number = result[0];
    const evenCount: number = result[1];

    // Display the result
    console.log("The frequency of odd numbers =", oddCount);
    console.log("The frequency of even numbers =", evenCount);
}

main();


/*
run:

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

*/

 



answered Nov 20, 2022 by avibootz
edited 4 days ago by avibootz

Related questions

...