Created
December 10, 2016 10:35
-
-
Save Erushenko/308b4ab9dfd0bdfae12e72ccc710376a to your computer and use it in GitHub Desktop.
Get the sum diagonals in the matrix on javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var matrixExample = [ | |
[ 1, 2, 3, 4 ], | |
[ 4, 5, 6, 5 ], | |
[ 7, 8, 9, 7 ], | |
[ 7, 8, 9, 7 ] | |
]; | |
function sumUpDiagonals(matrix) { | |
var sumDiagonals = {main: 0, second: 0}, | |
matrixLength = matrix.length; | |
for (var i = 0; i < matrixLength; i++) { | |
sumDiagonals.main += matrix[i][i]; | |
sumDiagonals.second += matrix[i][matrixLength-i-1]; | |
} | |
return sumDiagonals | |
} | |
console.log(sumUpDiagonals(matrixExample)) |
Hope this helps @calvinalee2006
let matrixExample = [
[1, 2, 3, 4],
[4, 5, 6, 5],
[7, 8, 9, 7],
[7, 8, 9, 7]
];
function sumUpDiagonals(matrix) {
// creating an object called sumDiagonals
let sumDiagonals = { primary: 0, secondary: 0 };
// creating a variable to get the length of the matrix
let matrixLength = matrix.length;
// iterating the matrix both from to sum from left and right diagnals
// primary = 1 + 5 + 9 + 7 = 22
// secondary = 4 + 6 + 8 + 7 = 25
for (var i = 0; i < matrixLength; i++) {
sumDiagonals.primary += matrix[i][i];
sumDiagonals.secondary += matrix[i][matrixLength - i - 1];
}
// return the object
return sumDiagonals;
}
console.log(sumUpDiagonals(matrixExample));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Could the thought process of this problem be explained a bit deeper in detail please?