Traversing matrix and summing the values

Asked

Viewed 45 times

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

1 answer

1


const arr = [
    [11, 2, 4],
    [4, 5, 6],
    [10, 8, -12]
]

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]
        console.log(elemento)
    })
    return Math.abs(diagonal1 - diagonal2)
}
diagonalDifference(arr)

Note that arr.forEach((elemento, ind) in each iteration a row of the matrix is returned.

Note that the main diagonal elements will increment na in the code that is represented by ind, which starts at 0 and goes up to 2.

While the elements of the secondary diagonal are decreasing, starting at 2 and decreasing until reaching 0 in the code this is done with len -1 -ind.

The image below will help in understanding:

inserir a descrição da imagem aqui

  • thank you very much, I was following this line of reasoning, but it was still not very clear, to be able to clearly understand the behavior of the code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.