Total possible ways of making sum of odd even indices elements equal in array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument.

The function should then try removing one such element from the array, upon removal of which, the sum of elements at odd indices is equal to the sum of elements at even indices. In the way, the function should count all the possible unique ways in which we can remove one element at a time to achieve the required combination.

For example −

If the input array is −

const arr = [2, 6, 4, 2];

Then the output should be 2 because, there are two elements 6 and 2 at indices 1 and 3 respectively that makes the combinations table.

When we remove 6 from the array −

[2, 4, 2] so the sum at odd indices = sum at even indices = 4

When we remove 2 from the array −

[2, 6, 4] so the sum at odd indices = sum at even indices = 6

Example

Following is the code −

const arr = [2, 6, 4, 2];
const possibleWays = (arr = []) => {
   const sum = new Array(arr.length);
   let res = 0;
   let oddSum = 0;
   let evenSum = 0;
   for (let i = 0; i < arr.length; ++i) {
      if (i % 2 === 0) sum[i] = (evenSum += arr[i]);
      else sum[i] = (oddSum += arr[i]);
   }
   for (let i = 0; i < arr.length; ++i) {
      if (i % 2 === 0) {
         if (2 * sum[i] - arr[i] + oddSum === 2 * (sum[i - 1] || 0) + evenSum) ++res;
      } else if (2 * sum[i] - arr[i] + evenSum === 2 * (sum[i - 1] || 0) + oddSum) {
         ++res;
      }
   }
   return res;
};
console.log(possibleWays(arr));

Output

Following is the console output −

2
raja
Published on 18-Jan-2021 09:17:15
Advertisements