Step 5 of 6
Grids: arrays of arrays
An array's elements can themselves be arrays. That gives you a grid (a 2D array): rows, each made of columns. Game boards, seating charts and spreadsheets all look like this.
fn main() {
let board = [
['X', 'O', 'X'],
['.', 'X', 'O'],
['O', '.', 'X'],
];
println!("center: {}", board[1][1]);
println!("bottom left: {}", board[2][0]);
for row in board {
println!("{} {} {}", row[0], row[1], row[2]);
}
}
center: X
bottom left: O
X O X
. X O
O . X
- The type of
boardis[[char; 3]; 3]: an array of 3 elements, where each element is a[char; 3](one row). board[1][1]reads in two steps:board[1]is the second row, and[1]picks the second cell in that row. By convention the row comes first, then the column.for row in boardhands you one row (a[char; 3]) per round.[[0; 4]; 3]builds 3 rows of 4 zeros: an array of value[0; 4], repeated 3 times.
Nested loops
To visit every cell, put one loop inside another: the outer loop picks the row, the inner one walks across it.
fn main() {
let mut seats = [[0; 4]; 3]; // 3 rows of 4 seats, 0 = free, 1 = taken
seats[0][1] = 1;
seats[2][0] = 1;
seats[2][3] = 1;
let mut taken = 0;
for row in 0..seats.len() {
for col in 0..seats[row].len() {
taken += seats[row][col];
}
}
println!("taken: {taken}");
for row in seats {
println!("{:?}", row);
}
}
taken: 3
[0, 1, 0, 0]
[0, 0, 0, 0]
[1, 0, 0, 1]
seats.len() is the number of rows (3) and seats[row].len() the number of columns in that row (4). Printing the whole grid with {:?} puts everything on one line ([[0, 1, 0, 0], [0, 0, 0, 0], [1, 0, 0, 1]]), so print it row by row when people need to read it.
Common mistakes
- Swapping row and column.
seats[3][0]is out of bounds (there are only 3 rows) even thoughseats[0][3]is fine. Decide "row first" and stick to it. - Rows of different lengths. Every row has the same type, so the same length:
[[1, 2, 3], [4, 5]]fails withexpected an array with a size of 3, found one with a size of 2. - Using
seats.len()for the columns. It counts rows. On a square grid that happens to give the right number, which hides the bug until a grid isn't square (here it would skip the last column).
Your task
Print the tic-tac-toe board one row per line with the cells separated by spaces, then count the cells with nested loops (compare each cell with 'X', 'O' and '.') and print the totals:
O X .
X X O
. O X
X: 4, O: 3, empty: 2
Challenge 2
Write row_sums(grid), which returns an array with the sum of each row of a 3 × 4 grid. For example, the grid [[1, 2, 3, 4], [5, 5, 5, 5], [0, 0, 0, 9]] gives [10, 20, 9].
Challenge 3
temps[day][reading] holds four readings for each of three days. Find the highest reading and where it is, then print it with day and reading numbered from 1 (as people count):
max 31 at day 2, reading 3
Find the position with loops; don't type the answer.
Previous: Looping over an array Next: A first look at Vec: a list that grows