Drill

ProblemsC# › patterns

Total the two diagonals

easypatternsGridsMathC#

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

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.

Solve it in Python →

Where you start

public int DiagonalTotal(List<List<int>> sheet) {
    
}

Worked examples

CallResult
DiagonalTotal(new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 4, 5, 6 }, new List<int> { 7, 8, 9 } })25
DiagonalTotal(new List<List<int>> { new List<int> { 1, 2 }, new List<int> { 3, 4 } })10
DiagonalTotal(new List<List<int>> { new List<int> { 5 } })5
DiagonalTotal(new List<List<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#
public int DiagonalTotal(List<List<int>> sheet) {
    int total = 0;
    int n = sheet.Count;
    for (int i = 0; i < n; i++) {
        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 C#