I been practicing my algorithm solving skill by solving HackerRank problems. However, one of the problems is giving me a difficult time to understand. It is about calculating absolute difference between sum of diagonals in a square matrix "arr".
If the square matrix is like this:
1 2 3
4 5 6
5 2 4
and the solution is like this:
1st diagonal = 1 + 5 + 4 = 10
2nd diagonal = 3 + 5 + 5 = 13
difference = |10 - 13| = 3 <-- This should appear!
So, I came up with this solution:
function diagonalDifference(arr) {
let first = 0;
let second = 0;
let diff = 0;
for(let i = 0; i < arr.length; i++){
first += arr[i][i];
second += arr[i][arr.length-i-1]
}
diff = first - second;
return Math.abs(diff);
}
However, I figure out all other parts except the "second += arr[i][arr.length-i-1]" part. I don't understand what [arr.length-i-1] is doing. Help me understand this.