Detecting Cycles
Many puzzles come in two parts. Part one asks for the state after 10 steps, and you just simulate it. Part two asks for the state after 1,000,000,000,000 steps. A direct simulation would never finish, let alone in an interpreter.
The key: if the number of possible states is limited, sooner or later a state has to come back. From then on everything repeats in the same pattern.
Remembering when a state first appeared
Store every state in a map, together with the step at which it was first seen:
seenAt := make(map[int]int) // state → step it was first seen
x := start
for step := 0; ; step++ {
if at, seen := seenAt[x]; seen {
// x first appeared at step at, and it's back now
return at, step - at
}
seenAt[x] = step
x = next(x)
}
The result is two numbers: first, the step where the repeating part begins, and length, how long the cycle is.
step: 0 1 2 3 4 5 6 7 8 9 10 11 12
state: 7 38 193 968 843 218 93 468 343 718 593 968 843
└────────── cycle: 8 ──────────┘
Skipping the cycle
After first, every length steps the state is the same. So the state at step n equals the state at step:
steps := first + (n-first)%length
From a number as big as a trillion, what's left is at most first + length - 1 steps, small enough to simulate. If n hasn't reached first yet, just simulate n steps.
In real puzzles the state is often bigger than one number, such as a whole grid. The approach is the same: turn the state into a map key, a string for example, and record its step.
Task
A lantern board shows one number every second. At second 0 it shows start, and every second the number is replaced by (x*mult + add) % mod (the next function is already there).
- Complete
findCycle(start, mult, add, mod int) (first, length int): the second at which the repeating part begins, and the length of the cycle. - Complete
valueAt(start, mult, add, mod, n int) int: the number shown at secondn. The tests use annas big as a trillion, so usefindCycleto skip the cycle.