Drill

ProblemsJavaScript › patterns

Total the two diagonals

easypatternsGridsMathJavaScript

A scoring sheet is a square grid, and the bonus is whatever sits on the two diagonals.

diagonalTotal(sheet: list<list<int>>) → int

Solve it in the editor →

Where you start

function diagonalTotal(sheet) {
  
}

Worked examples

CallResult
diagonalTotal([[1,2,3],[4,5,6],[7,8,9]])25
diagonalTotal([[1,2],[3,4]])10
diagonalTotal([[5]])5
diagonalTotal([])0

Hint

Walk one index down the grid. At row i the two diagonal cells are column i and column (last - i) — and on an odd grid those meet in the middle.

Reference solution in JavaScript
function diagonalTotal(sheet) {
  let total = 0;
  const n = sheet.length;
  for (let i = 0; i < n; i += 1) {
    total += sheet[i][i];
    if (i !== n - 1 - i) total += sheet[i][n - 1 - i];
  }
  return total;
}

The same problem in another language

More patterns problems in JavaScript