Problem overview
The function centerOfGrid receives a 3x3 grid of integers and returns the number in the center: the one in the middle row and the middle column. The grid has 3 rows, and every row has 3 numbers.
For the grid [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the answer is 5. For a grid with 7 in the middle and zeros around it, the answer is 7. For [[9, 8, 7], [6, -5, 4], [3, 2, 1]] it is -5: the center can be any number.
Approach
A grid is a table of numbers made of rows. In Kotlin, the parameter type Array<IntArray> describes it: an array whose items are themselves IntArray values, one for each row. Rows and columns are counted from 0, so a 3x3 grid has rows 0, 1 and 2, and the middle one is row 1. The same holds for columns.
The center is therefore at row 1, column 1. No loop is needed, because the position is fixed.
Step by step
- Pick the row.
grid[1]is the whole middle row, anIntArray. - Pick the column in that row. A second pair of brackets reads one number:
grid[1][1]. - Return it.
The solution in Kotlin
class Solution {
fun centerOfGrid(grid: Array<IntArray>): Int {
return grid[1][1]
}
}
Details worth knowing:
- Row first, then column.
grid[row][col]is two reads in a row: the first gives a row, the second reads a number from it. For the first example,grid[1]prints as4, 5, 6(usingjoinToString()) andgrid[1][1]is 5. Array<IntArray>versusList<List<Int>>.IntArrayholds primitiveIntvalues and has a fixed size.Array<IntArray>is an array of such rows. The indexing syntax is the same as for lists, sogrid[1][1]would also work on a list of lists.- Building a test grid. In a program of your own,
arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 5, 6), intArrayOf(7, 8, 9))creates the first example. The lesson's tests pass the grids in for you. sizecounts rows.grid.sizeis 3 here, the number of rows. For a grid of any odd size,grid[grid.size / 2][grid.size / 2]would be the center, but this lesson only needs the fixed 3x3 case.
Tracing the examples
First grid: grid[1] is the row [4, 5, 6], and index 1 of that row is 5.
Second grid: row 1 is [0, 7, 0], and index 1 of it is 7. The zeros around it don't matter.
Third grid: row 1 is [6, -5, 4], and index 1 is -5. Negative numbers need no special handling.
Edge cases and common mistakes
- Counting from 1.
grid[2][2]is the bottom-right corner, 9 in the first example, not the center. Indexes start at 0, so the middle of 0, 1 and 2 is 1. - Swapping the order. In a 3x3 grid,
grid[1][1]reads the same either way, but in general the first index is the row and the second is the column. Getting that right matters as soon as the grid isn't symmetric about its center. - Going out of range.
grid[3][0]throws anArrayIndexOutOfBoundsException, because a 3-row grid has no row 3. The valid indexes are 0 to 2.
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.
