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 −
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