Last active
May 29, 2023 06:34
-
-
Save lasverg/3cedfb161512583fc5ce1be1afb18fbd to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | 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
/* | |
Diagonal Difference Solution. | |
sample matrix = [[1,2,3], [4,5,6], [7,8,9]] | |
*/ | |
function diagonalDifference(matrix) { | |
// length of input matrix. | |
const length = matrix.length; | |
let diagonal1 = 0, diagonal2 = 0; | |
// Looping through the array and summing the diagonals. | |
for(let i = 0; i < length; i++){ | |
// Calculating the primary diagonal. | |
diagonal1 += matrix[i][i]; | |
// Reversing the second dimension of array to calculate secondary diagonal. | |
diagonal2 += matrix[length -1 - i][i] | |
} | |
// return absolute difference value. | |
return Math.abs(diagonal1 - diagonal2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment