Alternating sum of elements of a two-dimensional array using JavaScript


Problem

We are required to write a JavaScript function that takes in a 2-Dimensional array of m X n order of numbers containing the same number of rows and columns.

For this array, our function should count and return the following sum−

$\sum_{i=1}^m \sum_{j=1}^n (-1)^{i+j}a_{ij}$

Example

Following is the code −

 Live Demo

const arr = [
   [4, 6, 3],
   [1, 8, 7],
   [2, 5, 9]
];
const alternateSum = (arr = []) => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      for(let j = 0; j < arr[i].length; j++){
         const multiplier = (i + j) % 2 === 0 ? 1 : -1;
         sum += (multiplier * arr[i][j]);
      };
   };
   return sum;
};
console.log(alternateSum(arr));

Output

7

Updated on: 20-Apr-2021

182 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements