Skip to content

Instantly share code, notes, and snippets.

@lasverg
Last active May 29, 2023 06:34
Show Gist options
  • Save lasverg/3cedfb161512583fc5ce1be1afb18fbd to your computer and use it in GitHub Desktop.
Save lasverg/3cedfb161512583fc5ce1be1afb18fbd 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(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);
}
@derawi
Copy link

derawi commented Oct 13, 2022

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)
}

@oliveselow
Copy link

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)
}

@oliveselow
Copy link

Like

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment