-
-
Save naufaldi/62874ab0e73ef49909650531f24372f0 to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | JavaScript
This file contains hidden or 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(arr) { | |
// length of input array. | |
const length = arr.length; | |
let diagonal1 = 0, | |
diagonal2 = 0; | |
// Looping through the array and summing the diagonals. | |
for (let i = 0; i < arr.length; i++) { | |
// Calculating the primary diagonal. | |
diagonal1 += arr[i][i]; | |
// Reversing the second dimension of array to calculate secondary diagonal. | |
diagonal2 += arr[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