Skip to content

Instantly share code, notes, and snippets.

@joelethan
Created January 26, 2022 10:25
Show Gist options
  • Save joelethan/86ed2d3a5254b6176b4bb9a1694069fd to your computer and use it in GitHub Desktop.
Save joelethan/86ed2d3a5254b6176b4bb9a1694069fd to your computer and use it in GitHub Desktop.
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
function diagonalDifference(arr) {
// Write your code here
{
// Initialize sums of diagonals
let d1 = 0, d2 = 0;
const n = arr[0].length;
for (let i = 0; i < n; i++) {
// finding sum of primary diagonal
d1 += arr[i][i];
// finding sum of secondary diagonal
d2 += arr[i][n - i - 1];
}
// Absolute difference of the sums
// across the diagonals
return Math.abs(d1 - d2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment