Count the Groups, Not the Items
This is the classic "part two explodes" pattern. Part one asks for the result after 10 steps, and an ordinary simulation feels fine. Part two asks for 50 steps, and the number of things doubles over and over. After 50 steps there are more than a quadrillion of them. A slice with one element per thing will never fit in memory.
Identical things don't need storing one by one
Look at the question. Puzzles rarely care which item is which. Usually they only ask how many of each kind there are. If every blue sheet behaves the same way, one number is enough: how many blue sheets there are.
// one entry per sheet: grows without limit
sheets := []string{"blue", "red", "red", "green", ...}
// one number per colour: always three entries
counts := map[string]int{"blue": 4, "red": 0, "green": 1}
Each step, every colour adds to its new colours as many sheets as it has:
next := make(map[string]int)
for colour, n := range counts {
for _, becomes := range rules[colour] {
next[becomes] += n // n sheets at once, not one at a time
}
}
counts = next
The work per step is now proportional to the number of kinds, not the number of items. 50 steps with three colours means a few hundred operations, not quadrillions.
Still use a new map every step
Just like a grid simulation: every sheet changes at once. Write the result into next, not into the counts you're reading. Otherwise a sheet that just turned red changes again in the same step.
Watch the size of int
In Go, an int on a 64-bit computer holds up to about 9.2 × 10¹⁸. The numbers in this lesson still fit. If a puzzle talks about counts far bigger than that, check whether your results start going negative or wrapping around: that's a sign of overflow.
Task
An origami workshop has a strange rule. Every hour, every sheet of paper changes:
| Colour | Becomes |
|---|---|
blue | two red and one green |
red | two blue |
green | stays one green |
The rule is already in the rules map.
- Complete
after(start map[string]int, hours int) map[string]int: how many sheets of each colour there are afterhourshours, starting fromstart. Keep one number per colour. Don't change thestartmap. - Complete
total(counts map[string]int) int: the total number of sheets.
The tests compare your result with a one-by-one simulation for the first hours, then ask for the result after 50 hours.