-1
Hello guys I was doing a challenge of Hackerrank, and I came across a challenge where I asked to make the sum of the diagonals from right to left, and from left to right and finally returns the difference between the sums, solved as follows but only passed two tests:
const arr = [
[11, 2, 4],
[4, 5, 6],
[10, 8, -12]
]
function diagonalDifference(arr) {
var resultado;
var resultado;
for(let i = 0; i< 3; i++){
const a = arr[0][0] + arr[1][1] + arr[2][2];
const b = arr[0][2] + arr[1][1] + arr[2][0];
return Math.abs(b - a)
}
}
I found a better solution than mine but I would like your help to understand step by step how this code works:
function diagonalDifference(arr) {
let diagonal1 = 0;
let diagonal2 = 0;
const len = arr.length;
arr.forEach((elemento, ind) =>{
diagonal1 += elemento[ind]
diagonal2 += elemento[len -1 -ind]
})
return Math.abs(diagonal1 - diagonal2)
}
Behold What is a Table Test? How to Apply It?
– Augusto Vasques