Grids: arrays in arrays
In lesson 7 you drew a chessboard with two loops – but the board only existed as printed lines. To play on a board, it has to be data: an array of rows, and every row an array of cells. garden[row][col] first picks the row, then the cell in it – both counted from 0, row 0 at the top:
garden = [
["🌱", "🌱", "🥕"],
["🌱", "🦊", "🌱"],
["🥓", "🌱", "🌱"]
]
p garden[1][1]
p garden[2][0]
garden[0]To print a grid, turn every row into one line: map(&:join) joins each row into a string, and puts writes every string of an array on a line of its own. A cell changes with an assignment, garden[row][col] = … – here Chunky goes and gets the bacon:
garden[1][1] = "🌱"
garden[2][0] = "🦊"
puts garden.map(&:join)Typing a grid as arrays in arrays is fiddly. It is quicker to write it as strings, one per row, and let map(&:chars) cut every row into cells – the way back of map(&:join). Here # is a wall, F is Chunky and B the bacon. To find something, walk through the rows with each_with_index and ask every row for the index of what you are looking for:
cellar = [
"#####",
"#F..#",
"#.#B#",
"#####"
].map(&:chars)
cellar.each_with_index do |line, row|
col = line.index("B")
puts "bacon in row #{row}, column #{col}" if col
endA grid full of zeros – say, how many strips of bacon lie on each field of a baking tray – is quicker still with Array.new: Array.new(3, 0) is a row [0, 0, 0]. So Array.new(3, Array.new(3, 0)) should be a tray of 3 × 3 fields. Put 5 strips on the top left field and look:
tray = Array.new(3, Array.new(3, 0))
tray[0][0] = 5
p trayFifteen strips for the price of five! Array.new(3, row) made one row and put it into the tray three times – three labels on the same array, as in lesson 8. With a block, Array.new(3) { … } runs the block once for every row, and so builds three rows of their own. show_objects draws the difference:
good = Array.new(3) { Array.new(3, 0) }
good[0][0] = 5
p good
show_objects(tray: tray, good: good)All three arrows of tray end in the same row; good has three rows. Now to reading a grid. A row is simply grid[r]. A column is the cell at the same place in every row: map { |row| row[c] }. transpose flips the whole grid over its diagonal, so that its rows are the old columns. And the two diagonals are the cells where row and column are equal, and the cells where they add up to 2:
nine = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
p nine[1] # row 1
p nine.map { |row| row[2] } # column 2
p nine.transpose # all the columns
p 3.times.map { |i| nine[i][i] } # diagonal ↘
3.times.map { |i| nine[i][2 - i] } # diagonal ↙transpose has one more trick. Followed by map(&:reverse), it turns a grid 90° clockwise: the first column, read from the bottom up, becomes the first row. A grid that isn't square turns too – five rows of three become three rows of five, and the F lies on its side:
letter = ["###", "#..", "##.", "#..", "#.."].map(&:chars)
turned = letter.transpose.map(&:reverse)
puts letter.map(&:join)
puts
puts turned.map(&:join)Many games on grids ask about the neighbours of a cell: the up to eight cells around it. At the edge some of them are missing – and careful: grid[-1] is not nil but the last row, because negative numbers count from the end. So check the edges yourself before you look. next skips the rest of a loop's round:
def around(grid, row, col)
found = []
(row - 1..row + 1).each do |r|
(col - 1..col + 1).each do |c|
next if r == row && c == col # not the cell itself
next if r < 0 || c < 0 || r >= grid.size || c >= grid[r].size
found << grid[r][c]
end
end
found
end
p around(nine, 1, 1)
around(nine, 0, 0)The cell in the middle has all eight neighbours, the corner only three. Remember: grid[row][col], the row first; Array.new(n) { … } for rows of their own; transpose for the columns; and check the edges before you look at a neighbour.
winner(board): it returns "X" or "O" when that player has three in a line – in a row, a column or a diagonal – and nil when nobody has. Empty fields are ".", and three empty fields in a line are no win.# def winner(board)
# ... # "X" or "O" with three in a line - else nil
# end
# winner([%w[X O .],
# %w[O X .],
# %w[O . X]])
mine_counts(field): it returns a new grid of the same size, in which a mine "*" stays a mine and every other cell becomes the number of mines among its neighbours. around from above finds the neighbours for you.field = [
"*...",
"..*.",
"...."
].map(&:chars)
# def mine_counts(field)
# ... # "*" stays "*", every other cell: how many "*" are around it
# end
# puts mine_counts(field).map(&:join)