Last active
May 29, 2023 06:34
-
-
Save lasverg/3cedfb161512583fc5ce1be1afb18fbd to your computer and use it in GitHub Desktop.
Diagonal Difference | Solution | JavaScript
This file contains hidden or 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
/* | |
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); | |
} |
The matrix should be n x m, where n = m
, if your matrix isnt balanced you need to balance rows in the given matrix.
Please check out the example on below codesandbox link:
https://codesandbox.io/s/diagonal-difference-with-balance-matrix-61725c?file=/src/index.js
Although I dont know that expected outputs of given matixs, have a play around it and let me know if its makes sense or not.
function diagonalDifference(arr) {
const {a, b} = arr.reduce((acc, cur, i) => {
acc.a += arr[i][i]
acc.b += arr[arr.length - 1 - i][i]
return acc
}, {a: 0, b: 0})
return Math.abs(a - b)
}
function diagonalDifference(arr) {
let n = arr.length - 1
// caluclate the difference in every row
// e.g. first row: first - last element, second row: secondElement - (secondLast element)
arr = arr.map((el,i) => el[i]-el[n-i]).reduce((p,c)=>p+c)
return Math.abs(arr)
}
Alternative solution, just use the same For loop, to loop through in ascending and descending order:
function diagonalDifference(arr) { // Write your code here let firstDiagonalTotal = 0 let secondDiagonalTotal = 0 // firstDiagonal = arr[0][0] + arr[1][1] + arr[2][2] // secondDiagonal = arr[0][2] + arr[1][1] + arr[2][0] for (let i = 0, k = arr[0].length - 1; i < arr[0].length; i++, k--) { firstDiagonalTotal += arr[i][i] secondDiagonalTotal += arr[i][k] } return Math.abs(firstDiagonalTotal - secondDiagonalTotal) }
Like
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the matrix
I've implemented above matrix but I'm getting an error NAN. Can you please let me know what's the issue?
let matrix = [[3],[11,2,4],[4,5,6],[10,8,-12]]
console.log(diagonalDifference(matrix));
Your code isn't implementable for different types of matrix. I think you have to test this code on the different test cases like: