Skip to content

Instantly share code, notes, and snippets.

@Erushenko
Created December 10, 2016 10:35
Show Gist options
  • Save Erushenko/308b4ab9dfd0bdfae12e72ccc710376a to your computer and use it in GitHub Desktop.
Save Erushenko/308b4ab9dfd0bdfae12e72ccc710376a to your computer and use it in GitHub Desktop.
Get the sum diagonals in the matrix on javascript
var matrixExample = [
[ 1, 2, 3, 4 ],
[ 4, 5, 6, 5 ],
[ 7, 8, 9, 7 ],
[ 7, 8, 9, 7 ]
];
function sumUpDiagonals(matrix) {
var sumDiagonals = {main: 0, second: 0},
matrixLength = matrix.length;
for (var i = 0; i < matrixLength; i++) {
sumDiagonals.main += matrix[i][i];
sumDiagonals.second += matrix[i][matrixLength-i-1];
}
return sumDiagonals
}
console.log(sumUpDiagonals(matrixExample))
@calvinalee2006
Copy link

Could the thought process of this problem be explained a bit deeper in detail please?

@sdkdeepa
Copy link

sdkdeepa commented May 31, 2022

Hope this helps @calvinalee2006

let matrixExample = [
  [1, 2, 3, 4],
  [4, 5, 6, 5],
  [7, 8, 9, 7],
  [7, 8, 9, 7]
];

function sumUpDiagonals(matrix) {
  // creating an object called sumDiagonals
  let sumDiagonals = { primary: 0, secondary: 0 };

  // creating a variable to get the length of the matrix
  let matrixLength = matrix.length;

  // iterating the matrix both from to sum from left and right diagnals
  // primary = 1 + 5 + 9 + 7  = 22
  // secondary = 4 + 6 + 8 + 7 = 25

  for (var i = 0; i < matrixLength; i++) {
    sumDiagonals.primary += matrix[i][i];
    sumDiagonals.secondary += matrix[i][matrixLength - i - 1];
  }

  // return the object
  return sumDiagonals;
}

console.log(sumUpDiagonals(matrixExample)); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment