Skip to content

Instantly share code, notes, and snippets.

@hassan-maavan
Created September 19, 2020 06:28
Show Gist options
  • Save hassan-maavan/6d0028c06ce73840f05e232b54c3ced5 to your computer and use it in GitHub Desktop.
Save hassan-maavan/6d0028c06ce73840f05e232b54c3ced5 to your computer and use it in GitHub Desktop.
Create a function that receives a (square) matrix and calculates the sum of both diagonals (main and secondary) Matrix = array of n length whose elements are n length arrays of integers. 3x3 example: https://www.codewars.com/kata/5592fc599a7f40adac0000a8/javascript
function sum(matrix) {
let i = 0;
let sum = 0;
matrix.forEach(array => {
sum += array[i];
sum += array[array.length - i -1]
i++;
if(i >= array.lenght) {
i = 0;
}
})
return sum;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment