Problem Solving with Go course

GridsSimulating Step by Step

Problem Solving with Go

Display

Theme

Grids · Test exercise

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.

  1. Complete step(grid []string) []string: the garden after one night. Don't change the grid you're given.
  2. Complete settle(grid []string) (int, []string): run step until a night changes nothing. Return how many nights changed something, and the garden after them.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

var dirs4 = [][2]int{{-1, 0}, {1, 0}, {0, -1}, {0, 1}}

// mossAround counts the '*' cells up, down, left and right of (r, c).
func mossAround(grid []string, r, c int) int {
	n := 0
	for _, d := range dirs4 {
		nr, nc := r+d[0], c+d[1]
		if nr >= 0 && nr < len(grid) && nc >= 0 && nc < len(grid[nr]) && grid[nr][nc] == '*' {
			n++
		}
	}
	return n
}

// step returns the garden one night later: every '.' with at least two '*'
// neighbours (up, down, left, right) becomes '*'. Nothing else changes.
// The grid passed in is left as it was.
func step(grid []string) []string {
	// TODO: build a new grid; read neighbours from grid, never from the new one
	return grid
}

// settle runs step until a night changes nothing. It returns how many nights
// changed something, and the garden after them.
func settle(grid []string) (int, []string) {
	// TODO
	return 0, grid
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	garden := strings.Split(strings.TrimSpace(string(data)), "\n")
	nights, final := settle(garden)
	fmt.Println("nights until nothing changes:", nights)
	fmt.Println(strings.Join(final, "\n"))
}
Go runtime not loaded yet

5 lines · 55 B of the 1 MB limit. Submit always uses the lesson's own input.