Created
January 26, 2022 10:25
-
-
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.
This file contains 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
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