How to count the odd and even sum of pairs in an array with Node.js

1 Answer

0 votes
function countOddAndEvenSumOfPairs(arr) {
    let totalEven = 0, totalOdd = 0;
    const size = arr.length;
 
    for (let i = 0; i < size; i++) {
        if (arr[i] % 2 === 0) {
            totalEven++;
        } else {
            totalOdd++;
        }
    }
 
    // For all the even elements -> sum of the pair will be even
    let evenPairs = ((totalEven * (totalEven - 1)) / 2);
 
    // For all the odd elements -> sum of the pair will be even
    evenPairs += ((totalOdd * (totalOdd - 1)) / 2);
 
    // All even elements * all odd element -> sum of the pair will be odd
    let oddPairs = totalEven * totalOdd;
 
    return [evenPairs, oddPairs];
}
 
const arr = [1, 2, 3, 4, 5];
 
// 1 + 3, 1 + 5, 2 + 4, 3 + 5 = 4 Even
// 1 + 2, 1 + 4, 2 + 3, 2 + 5, 3 + 4, 4 + 5 = 6 Odd
   
const [evenPairs, oddPairs] = countOddAndEvenSumOfPairs(arr);
 
console.log("Total Even Sum = " + evenPairs);
console.log("Total Odd Sum = " + oddPairs);
 
 
 
/*
run:
 
Total Even Sum = 4
Total Odd Sum = 6
 
*/

 



answered Jun 17, 2024 by avibootz

Related questions

1 answer 140 views
1 answer 133 views
1 answer 107 views
1 answer 117 views
1 answer 98 views
...