Problem overview
The method 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. For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the answer is 5. For [[0, 0, 0], [0, 7, 0], [0, 0, 0]] it is 7. The center can be any number in the allowed range, a negative one too: for [[9, 8, 7], [6, -5, 4], [3, 2, 1]] it is -5.
Approach
A grid is a table of numbers organised in rows. In Scala, the type Array[Array[Int]] describes it as an array whose items are themselves arrays of integers: each item of the outer array is one row, and each row holds the numbers of that row, one per column.
Rows and columns are counted from 0, like every index in Scala. A grid with 3 rows has the row indexes 0, 1 and 2, and each row has the column indexes 0, 1 and 2. The middle of 0, 1 and 2 is 1, in rows and columns alike. So the center is at row 1, column 1, and the problem is a single lookup.
Step by step
- Pick the row.
grid(1)is the whole middle row, anArray[Int]. For the first example, it is[4, 5, 6]. - Pick the column in that row. Indexing the row again,
grid(1)(1), gives the integer at row 1 and column 1. - Return it. The method is one line.
The solution in Scala
class Solution {
def centerOfGrid(grid: Array[Array[Int]]): Int = {
return grid(1)(1)
}
}
A few Scala details:
- Scala reads an array item with parentheses, not square brackets.
grid(1)(1)is two lookups in a row: the first returns the row, and the second reads from that row. - The row index comes first and the column index second:
grid(row)(col). For the corner at the top right you would writegrid(0)(2), and for the bottom leftgrid(2)(0). - An
Arrayreports its size withlength. Heregrid.lengthis 3 for the number of rows, andgrid(0).lengthis 3 for the number of columns. - Printing an array directly, as in
println(grid(1)), shows an object identifier, not its items. To see the items, usegrid(1).mkString("[", ", ", "]"), which gives[4, 5, 6]for the first example.
Tracing an example
For the first example, grid(1) is the row [4, 5, 6], and grid(1)(1) is the item at index 1 of that row: 5. For the third example the middle row is [6, -5, 4] and the result is -5.
Edge cases and common mistakes
- Starting from 1. Counting rows as 1, 2 and 3 would send you to
grid(2)(2), the bottom-right corner (9 in the first example). Indexes start at 0. - Mixing up row and column.
grid(row)(col)reads the row first. For the center the two indexes are equal, so a swap goes unnoticed here, but it matters for other cells. - Square brackets.
grid[1][1]is not a lookup in Scala. Square brackets are for type parameters, as inArray[Int]. - Other grid sizes. The fixed index 1 is right only for a 3×3 grid. For a grid of any odd size, the middle index would be the size divided by 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.
