Problem overview
The function center_of_grid takes a 3×3 grid of integers, grid, and returns the number in its center: the one in the middle row and the middle column. The grid has exactly 3 rows with 3 numbers each, and every number is between -1000 and 1000.
For [[1, 2, 3], [4, 5, 6], [7, 8, 9]] the result is 5: the middle row is [4, 5, 6] and its middle number is 5. For [[9, 8, 7], [6, -5, 4], [3, 2, 1]] it is -5, because the center can be a negative number too.
Approach
In Rust the grid has the type Vec<Vec<i32>>: a vector whose items are themselves vectors. Each inner vector is one row. Indexing works one level at a time: grid[1] is the whole middle row, and grid[1][1] is the number at row 1, column 1.
Rows and columns are counted from 0, so a grid with three of each has rows 0, 1 and 2, and the middle one is 1. The same holds for the columns. The center is therefore grid[1][1].
The same idea works for any position: the first index chooses the row and the second chooses the column. In the first example, grid[0][2] is 3, the last number of the top row, and grid[1][1] is 5, where the middle row and the middle column cross. No loop and no arithmetic are needed because the grid has a fixed size.
Step by step
- Pick the middle row with
grid[1]. - Pick the middle number of that row with a second index,
[1]. - Return it as the last expression. The line has no semicolon, so its value is what the function returns.
The solution in Rust
impl Solution {
fn center_of_grid(grid: Vec<Vec<i32>>) -> i32 {
grid[1][1]
}
}
Some details worth knowing:
- No semicolon, no
return. In Rust a block's value is its last expression. Adding a semicolon would turn the line into a statement, and the function would then return nothing, which doesn't matchi32. - Row first, then column.
grid[row][col]is read left to right. For the first example,grid[1]is[4, 5, 6]andgrid[1][1]is5. i32isCopy. Indexing gives a copy of the number, so returning it doesn't move anything out of the grid.- Out-of-range indexes panic. Reading
grid[3]would stop the program. For this lesson's grids, the indexes 0, 1 and 2 are all valid, and 1 is always in range.
Edge cases and common mistakes
- Counting from 1.
grid[2][2]is the bottom-right corner, 9 in the first example. The middle is index 1, not 2. - Swapping row and column. For a 3×3 grid, the center is the same either way, but
grid[0][1]andgrid[1][0]are different cells, so keep the order in mind for later problems. - Taking a row instead of a number.
grid[1]alone is aVec<i32>, which doesn't match the return type. - Looking only at the middle row. The center of the example
[[0, 0, 0], [0, 7, 0], [0, 0, 0]]is 7: the other numbers don't matter. - Negative numbers. There is nothing special to do for them:
-5is returned like any otheri32.
Testing
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]gives5.[[0, 0, 0], [0, 7, 0], [0, 0, 0]]gives7.[[9, 8, 7], [6, -5, 4], [3, 2, 1]]gives-5.
