Question:
Principal Diagonal — The principal diagonal in a matrix identifies those elements of the matrix running from North-West to South-East.
Secondary Diagonal — the secondary diagonal of amatrix identifies those elements of the matrix running from North-East to South-West.
For example:
matrix: [1, 2, 3] [4, 5, 6] [7, 8, 9]
principal diagonal: [1, 5, 9]
econdary diagonal: [3, 5, 7]
Task
Your task is to find which diagonal is “larger”: which diagonal has a bigger sum of their elements.
- If the principal diagonal is larger, return
"Principal Diagonal win!"
- If the secondary diagonal is larger, return
"Secondary Diagonal win!"
- If they are equal, return
"Draw!"
Note: You will always receive matrices of the same dimension.
Solution:
function diagonal(matrix){ var sumNw=0, sumNe = 0; for (var i=0; i<matrix.length; i++) { sumNw += matrix[i][i]; sumNe += matrix[i][matrix.length-1-i]; } if (sumNw === sumNe) { return 'Draw!'; } else { return sumNw > sumNe ? 'Principal Diagonal win!' : 'Secondary Diagonal win!'; } }
The question and answer are referred from https://www.codewars.com/kata/5a8c1b06fd5777d4c00000dd