Skip to content

Instantly share code, notes, and snippets.

@cobiwave
Forked from lasverg/diagonal-difference.js
Created September 12, 2018 14:45
Show Gist options
  • Save cobiwave/25dfafc2f528958fb945cf4b0405dfa6 to your computer and use it in GitHub Desktop.
Save cobiwave/25dfafc2f528958fb945cf4b0405dfa6 to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | JavaScript
/*
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 += a[i][i];
// Reversing the second dimension of array to calculate secondary diagonal.
diagonal2 += a[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