Skip to content
advent of code 2018

day 09

marble mania

approach

the circle of marbles is a collections.deque with the current marble kept at its right end, so every move is a rotation and an append or a pop. a normal marble rotates one step and is appended. every 23rd marble rotates seven steps back, pops the marble there into the current player's score, and rotates one forward again.

the committed file only has the part 2 setup: it multiplies the last marble by 100 before the loop, and part 1 is the same loop without that line. the high score, max(players), isn't printed.

the trick

keep the current marble at one end of a deque, so moving around the circle is rotate and inserting or removing is O(1).

python
for move in range(1,last_marble+1):
	if move%23==0:
		marbles.rotate(7)
		players[move%num]+=(marbles.pop()+move)
		marbles.rotate(-1)
	else:
		marbles.rotate(-1)
		marbles.append(move)