Skip to content

Instantly share code, notes, and snippets.

@juelvaldivia
Created August 28, 2020 19:20
Show Gist options
  • Save juelvaldivia/7a48fb9671f45029a7349a1b826879ff to your computer and use it in GitHub Desktop.
Save juelvaldivia/7a48fb9671f45029a7349a1b826879ff to your computer and use it in GitHub Desktop.
function diagonalDifference(matrix) {
// declara los arreglos vacios a sumar
const leftDiagonal = [];
const rightDiagonal = [];
// regresa un arreglo con la diagonal de izquierda a derecha de la matriz
matrix.forEach((element, position) => {
// obtiene la posicion invertida de la matriz
const positionRight = (matrix.length - (position + 1));
// agrega los valores en sus correspondientes arreglos
leftDiagonal.push(element[position]);
rightDiagonal.push(element[positionRight]);
});
// suma todas las cantidades del arreglo de izquierda a derecha
const totalLeftDiagonal = leftDiagonal.reduce((accumulator, current) => {
return accumulator + current
}, 0)
// suma todas las cantidades del arreglo de izquierda a derecha
const totalRightDiagonal = rightDiagonal.reduce((accumulator, current) => {
return accumulator + current
}, 0)
// regresa la resta detectando valores absolutos
return Math.abs(totalLeftDiagonal - totalRightDiagonal)
}
const matrix = [
[0, 15, 2, 1],
[8, 9, 8, 5],
[3, 3, 16, 7],
[12, 5, 22, 5]
]
const difference = diagonalDifference(matrix)
console.log(difference)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment