Advent of Code: Day #15 - Rambunctious Recitation

15th of December 2020 |

3 - 4 minutes

Introduction

Today we are challenged to implementing Van Eck's sequence.

Task One & Two

For n >= 1, if there exists an m < n such that a(m)=a(n), take the largest such m and set a(n+1)=n-m; otherwise a(n+1)=0.

Reading in the data

Todays input was just a list of 6 numbers so I just defined them in an array in code.

The Solution

I created a dictionary that will hold all numbers that have been said as keys with the value being a list of indices of when the number was last spoken. We then run a loop until we get to the specified turn (2020 for Part One and 30000000 for Part Two). Each iteration we increment the turn, get the age array from memory or None if the number hasn't be spoken before, we then add the last time the number was spoken to memory and finally calculate the age (Or last time we saw the number).

Python Copy
def tasks(numbers, limit):
memory = {num: [index + 1] for index, num in enumerate(numbers)}
turn = len(numbers)
last_spoken = numbers[-1]
memory[last_spoken] = [None]

while turn < limit:
turn += 1
# Faster than memory.get()
try:
age = memory[last_spoken]
except KeyError:
age = [None]

if age[0] is None:
memory[last_spoken] = [turn - 1]
age = 0
else:
age.append(turn - 1)
# If RAM is an issue un-comment the lines below
# if len(age) >= 3:
# age = age[1:]
memory[last_spoken] = age
age = age[-1] - age[-2]

last_spoken = age

return last_spoken

Leaderboard Code: 353270-1fc6ef28

Github Repository A link to the github repo containing all the days.

main.py A direct download of the main.py script

1.0Kb