Lesson 5.13 · Write it
Down the diagonal
A functionPython or Java9 tests, 5 of them hidden
On a phone? Put the lines in order instead
A board game is played on a square grid of whole numbers. Write a function that returns the total of the cells on the diagonal that runs from the top left corner to the bottom right corner. In Python the grid is a list of rows; in Java it is an int[][].
- The diagonal is the cell in row 0, column 0, then row 1, column 1, and so on to the last row and column.
- The grid is square: it has as many rows as columns, and at least one of each.
- The values can be negative. Every value is between -1000 and 1000, and the grid has at most 20 rows.
Only the number your function returns is checked.
def diagonal_total(grid: list[list[int]]) -> int
Examples
Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.
- diagonal_total([[2, 5], [7, 3]]) should return 5: 2 in row 0, column 0, plus 3 in row 1, column 1
- diagonal_total([[6]]) should return 6: one cell is the whole diagonal (rule 2)
- diagonal_total([[1, 0, 4], [2, 5, 8], [3, 9, 7]]) should return 13: a 3 by 3 grid: 1 + 5 + 7
- diagonal_total([[-3, 2], [4, -1]]) should return -4: negative values on the diagonal (rule 3)
public static int diagonalTotal(int[][] grid)
Running Java here comes later. You can put this answer's lines in order instead. You can still write your Java answer (it stays while this page is open) and compare it with our worked solution. Or try this exercise in Python.Checking whether Java answers can run here.
Examples
Your function is tested on 9 cases: the 4 examples below, and 5 hidden ones that check the rules above.
- diagonalTotal(new int[][]{new int[]{2, 5}, new int[]{7, 3}}) should return 5: 2 in row 0, column 0, plus 3 in row 1, column 1
- diagonalTotal(new int[][]{new int[]{6}}) should return 6: one cell is the whole diagonal (rule 2)
- diagonalTotal(new int[][]{new int[]{1, 0, 4}, new int[]{2, 5, 8}, new int[]{3, 9, 7}}) should return 13: a 3 by 3 grid: 1 + 5 + 7
- diagonalTotal(new int[][]{new int[]{-3, 2}, new int[]{4, -1}}) should return -4: negative values on the diagonal (rule 3)