Skip to content

Instantly share code, notes, and snippets.

@naufaldi
Forked from lasverg/diagonal-difference.js
Created July 8, 2019 02:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naufaldi/62874ab0e73ef49909650531f24372f0 to your computer and use it in GitHub Desktop.
Save naufaldi/62874ab0e73ef49909650531f24372f0 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(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