Last active
August 8, 2022 16:31
-
-
Save Stefanacef/9e3a8b98b51b8c349b8c82950fb79fa9 to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | JavaScript
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
let arr = [ | |
[-1, 1, -7, -8], | |
[-10, -8, -5, -2], | |
[0, 9, 7, -1], | |
[4, 4, -2, 1], | |
]; | |
function diagonalDifference(arr) { | |
// Extraction of the primary diagonal | |
let left = arr | |
.map((e, i) => { | |
return arr[i][i]; | |
}) | |
.reduce((acc, e) => acc + e); | |
//Extraction of the secondary diagonal. | |
let right = arr | |
.map((e, i) => { | |
return arr[i][arr.length - i - 1]; | |
}) | |
.reduce((acc, e) => acc + e); | |
//difference | |
let dif = left - right; | |
// return absolute difference value. | |
return Math.abs(dif); | |
} | |
console.log(diagonalDifference(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment