Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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
Advertisements