Problem overview
The function centerOfGrid receives grid, a 3×3 table of integers, and returns the number in its center: the one in the middle row and the middle column. The grid has exactly 3 rows, and every row has exactly 3 numbers between -1000 and 1000.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the middle row is [4, 5, 6], and its middle number is 5. For [[0, 0, 0], [0, 7, 0], [0, 0, 0]] the answer is 7, and for [[9, 8, 7], [6, -5, 4], [3, 2, 1]] it is -5: the center can be any number, a negative one too.
Approach
In Go, a grid of integers has the type [][]int: a slice whose items are themselves slices of int. Each inner slice is one row. That gives two levels of indexing:
grid[row]is a whole row, an[]int;grid[row][col]is the single number at that row and column.
Rows and columns are counted from 0, as every index in Go is. A 3×3 grid has rows 0, 1 and 2 and columns 0, 1 and 2, so the middle row is row 1 and the middle column is column 1. The center is grid[1][1]. No loop and no arithmetic are needed.
Step by step
- Pick the middle row with the first index:
grid[1]. - Pick the middle column of that row with the second index:
grid[1][1]. - Return the number. It has the type
int, which matches the function's result.
The solution in Go
func centerOfGrid(grid [][]int) int {
return grid[1][1]
}
Running it on the three examples gives these results:
[[1 2 3] [4 5 6] [7 8 9]] -> 5
[[0 0 0] [0 7 0] [0 0 0]] -> 7
[[9 8 7] [6 -5 4] [3 2 1]] -> -5
Details worth knowing:
- The row comes first. In
grid[r][c],rpicks the row andcthe column. Reading it from left to right matches how you describe a cell: "row 1, then column 1". - A slice of slices need not be square. Nothing in the type
[][]intsays that every row has the same length. This lesson promises 3 rows of 3 numbers, which is why a fixed index is safe here. - Indexes are checked at run time. If a row were too short, or the grid had fewer than 2 rows,
grid[1][1]would stop the program with an "index out of range" panic. - Rows are slices.
grid[1]on its own is the slice[4 5 6]for the first example, which could be passed to another function or looped over.
Edge cases and common mistakes
- Counting from 1.
grid[2][2]is the bottom-right corner, not the center. The middle of the indexes 0, 1 and 2 is 1. - Swapping row and column. For a 3×3 grid the center sits on the diagonal, so
grid[1][1]is the same either way, but in other cells the order matters: in the first example,grid[0][2]is 3 andgrid[2][0]is 7. - Writing
grid[1, 1]orgrid[1:1]. Go has no comma indexing. Each index goes in its own pair of brackets. - Believing the middle number is the largest. The center is about the position. In the second example it is 7, the only non-zero number, and in the third it is -5, the smallest.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives 5.[[0, 0, 0], [0, 7, 0], [0, 0, 0]]gives 7.[[9, 8, 7], [6, -5, 4], [3, 2, 1]]gives -5.
