day 15


well this was a weird day... my main struggle was just making basic errors. the input isn't even on a separate page and it's only one line with numbers separated by commas, so i took out my input.split('\n') line. i've also imported defaultdict since that means that if i try to access a key that isn't there, it creates it with a default value (0, since i've used defaultdict(int)) instead of throwing an error.

from collections import defaultdict
# input
with open('15.txt', 'r') as file:
    input = file.read()
# get num list
num_list = [int(num) for num in input.split(',')]
# start dict
num_dict = defaultdict(int)
# key is a number
# value is the position it was last in
# if key isn't in the dict it's added with default 0

we start off by putting in the starting numbers (from the input):

# put starting numbers in dict
i = 0
while i < len(num_list):
    num = num_list[i]
    i += 1
    num_dict[num] = i

we now have a dict where the keys are numbers that have already been said, and the values are the (one-indexed) position when that number was said (so an input of 1,2,4 gives a starting [default]dict of {1: 1, 2: 2, 4: 3}).

we want to continue generating numbers until we hit the 2020th number. first we get the position (pos) of the last number spoken (num), and then the value in the dict is set to i (since num was the i^th number). if pos is 0, then that means num was said for the first time as the i^th number, and our next number will be 0. otherwise, our next number is the difference between when num was said and when it was said before that, which is given by i - pos.

while i < 2020:
    # get the position of the number spoken
    pos = num_dict[num]
    # save new position for current number
    num_dict[num] = i
    # get the next number
    if pos == 0: # number has not come up
        num = 0
    else: # number has come up
        num = i - pos
    i += 1

when this loop terminates, we have the 2020th number:

print(str(i) + '^th number: ' + str(num))

for part b... it's literally the same but we want the 30 millionth number. i don't know if there's even a way to get a number in this sequence without just generating the entire sequence, since you need to use previous positions of a number to get the next number.. it's not like there's a pattern you can get from taking repeated differences.

so i just swapped 2020 for 30000000 in the loop above and added an extra line within the while loop to show the current value of i (as reassurance that the loop's still going):

print('i = ' + str(i), end = '\r', flush = True)

Files

15a.py 995 bytes
Dec 15, 2020
15b.py 1 kB
Dec 15, 2020

Get aoc 2020

Leave a comment

Log in with itch.io to leave a comment.