Simulating Step by Step
Many grid puzzles are simulations: on every step, every cell changes by a rule that depends on its neighbours. The question is usually "what does the grid look like after 10 steps?" or "after how many steps does the grid stop changing?".
The trap: changing the grid while reading it
Rules like these apply all at once: every cell sees the state before the step began. If you change cells in the same grid while reading their neighbours, cells to the right or below will see changes that shouldn't have happened yet:
before right wrong (changed in place)
.** *** ***
*.. **. ***
The bottom-right cell has only one mossy neighbour in the starting state. It only changes on the next step, unless you mistakenly read a neighbour that has just changed.
The fix: read from the old grid, write to a new one.
next := make([]string, len(grid))
for r, line := range grid {
row := []byte(line) // a copy to write to
for c := range row {
if row[c] == '.' && mossAround(grid, r, c) >= 2 { // read from grid
row[c] = '*'
}
}
next[r] = string(row)
}
[]byte(line) makes a new copy, so changing row doesn't touch grid. That's why step is safe: the grid you pass in stays the same.
Until it settles
For "how many steps until nothing changes", keep stepping and compare each result with the grid before it. The simplest way to compare two []string is to join each into one string with strings.Join (or use slices.Equal).
Task
Moss is growing in a rock garden. On the map, * is moss, . is bare ground and # is stone. Every night, every . with at least two * neighbours (up, down, left, right) becomes *. Moss never disappears, and stone never changes. mossAround is ready.
- Complete
step(grid []string) []string: the garden after one night. Don't change the grid you're given. - Complete
settle(grid []string) (int, []string): runstepuntil a night changes nothing. Return how many nights changed something, and the garden after them.