Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,693 questions

57,001 answers

573 users

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

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) {

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

    let odd = 0;
    let even = 0;

    for (let i = 0; i < rows; i++) {
        for (let j = 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() {

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

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

    // 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 Aug 29, 2021 by avibootz
edited Jul 1 by avibootz

Related questions

...