Drill

ProblemsJava › patterns

Total the two diagonals

easypatternsGridsMathJava

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

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

Java 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

int diagonalTotal(List<List<Integer>> sheet) {
    
}

Worked examples

CallResult
diagonalTotal(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2, 3), Main.<Integer>ls(4, 5, 6), Main.<Integer>ls(7, 8, 9)))25
diagonalTotal(Main.<List<Integer>>ls(Main.<Integer>ls(1, 2), Main.<Integer>ls(3, 4)))10
diagonalTotal(Main.<List<Integer>>ls(Main.<Integer>ls(5)))5
diagonalTotal(Main.<List<Integer>>ls())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 Java
int diagonalTotal(List<List<Integer>> sheet) {
    int total = 0;
    int n = sheet.size();
    for (int i = 0; i < n; i++) {
        total += sheet.get(i).get(i);
        if (i != n - 1 - i) total += sheet.get(i).get(n - 1 - i);
    }
    return total;
}

The same problem in another language

More patterns problems in Java