settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: Diagonal Sums in JavaScript matrix

+2 votes

A square matrix of numbers comes as an array of strings, each string holding numbers (space separated). Write a JS function that finds the sum at the main and at the secondary diagonals.

The input comes as array of arrays, containing number elements (2D matrix of numbers).

Examples:

Input:
[[20, 40],
 [10, 60]]

Output:
80 50


Input:
[[3, 5, 17],
 [-1, 7, 14],
 [1, -8, 89]]

Output:
99 25

The output is printed on the console, on a single line separated by space. First print the sum at the main diagonal, then the sum at the secondary diagonal.

asked in JavaScript category by user nikole

1 Answer

+1 vote

Here's my JS matrix solution:

function diagonalSums(matrix) {

    let mainSum = 0, secondarySum = 0;
    for (let row = 0; row < matrix.length; row++) {
        mainSum += matrix[row][row];
        secondarySum += matrix[row][matrix.length - row - 1];
    }
    console.log(mainSum + ' ' + secondarySum);
}

diagonalSums([[20, 40], [10, 60]]);

 

answered by user mitko
...