RustArena

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

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

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