Skip to content
advent of code 2017

day 06

memory reallocation

approach

the banks are a list of integers. one step picks the fullest bank (ties go to the lowest index), empties it, and hands its blocks out one at a time to the following banks, wrapping around.

a dict maps each configuration, as a tuple, to the step at which it was first seen. the loop runs until a configuration repeats; the step count is part 1, and the distance back to the first sighting is the cycle length for part 2. both come out of the same run.

the trick

store when each state was first seen, not just that it was seen, and the cycle length falls out for free.

python
def steps(blocks):
    visited = {}
    i = 0
    while (tup := tuple(blocks)) not in visited:
        visited[tup] = i
        step(blocks)
        i += 1
    return i, i - visited[tup]