1
I’m trying to calculate the main diagonal of an array in Js, someone could help ?
function calcularDiagonal(matriz) {
let soma = 0;
for(let i = 0; i < matriz.length; i++) {
for(let j = 0; j < matriz.length; j++) {
if( matriz[i] == matriz[j]) {
soma += matriz[i];
}
}
}
return soma;
}
const matriz = [[1,2,3,4,4,4,5,5,5]];
console.log(calcularDiagonal(matriz));
I did so but is returning a wrong result, which is :
01,2,3,4,4,4,5,5,5
But it should give the result 10, if anyone can see what’s wrong, thank you.
Diagonal is a property of square matrices. No diagonal non-square matrices are calculated. The matrix in your example is a line matrix therefore without diagonal.
– Augusto Vasques
@Augustovasques removed my answer. Virgilio’s is fine and I already gave it to him
+1
:)– Sergio