Skip to content

Instantly share code, notes, and snippets.

@lasverg
Last active May 29, 2023 06:34
Show Gist options
  • Save lasverg/3cedfb161512583fc5ce1be1afb18fbd to your computer and use it in GitHub Desktop.
Save lasverg/3cedfb161512583fc5ce1be1afb18fbd 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 += 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);
}
@oliveselow
Copy link

Like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment