Total the two diagonals
A scoring sheet is a square grid, and the bonus is whatever sits on the two diagonals.
- The grid is square.
- Add every cell on the top-left to bottom-right diagonal, and every cell on the other one.
- On an odd-sized grid the centre belongs to both diagonals, and is counted once.
- An empty grid totals zero.
diagonalTotal(sheet: list<list<int>>) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int diagonalTotal(std::vector<std::vector<int>> sheet) {
}
Worked examples
| Call | Result |
|---|---|
diagonalTotal(std::vector<std::vector<int>>{std::vector<int>{1, 2, 3}, std::vector<int>{4, 5, 6}, std::vector<int>{7, 8, 9}}) | 25 |
diagonalTotal(std::vector<std::vector<int>>{std::vector<int>{1, 2}, std::vector<int>{3, 4}}) | 10 |
diagonalTotal(std::vector<std::vector<int>>{std::vector<int>{5}}) | 5 |
diagonalTotal(std::vector<std::vector<int>>{}) | 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 C++
int diagonalTotal(std::vector<std::vector<int>> sheet) {
int total = 0;
int n = static_cast<int>(sheet.size());
for (int i = 0; i < n; i++) {
total += sheet[i][i];
if (i != n - 1 - i) total += sheet[i][n - 1 - i];
}
return total;
}