Day 15 (refactoring)

This commit is contained in:
Sebastian Seedorf
2020-12-15 21:18:55 +01:00
parent 11d1b8c4c6
commit 5a2b9fe23f
3 changed files with 25 additions and 28 deletions

21
day15/common.py Normal file
View File

@@ -0,0 +1,21 @@
from functools import reduce
def yield_numbers(line: str, target: int):
nums = {}
turn = 0
last_spoken = 0
for starting in map(int, line.split(",")):
nums[last_spoken] = turn
turn += 1
last_spoken = starting
yield turn, last_spoken
for t in range(turn, target):
n = t - nums[last_spoken] if last_spoken in nums else 0
nums[last_spoken] = t
last_spoken = n
yield t+1, last_spoken
def get_target(line: str, target: int):
return reduce(lambda a, b: b, yield_numbers(line, target))

View File

@@ -1,22 +1,10 @@
#!/usr/bin/env python3
from collections import defaultdict
from day15.common import get_target
lines = (x.strip() for x in open("input.txt"))
TARGET = 2020
for line in lines:
print(line)
nums = defaultdict(list)
turn = 0
last_spoken = 0
for starting in map(int, line.split(",")):
nums[starting] = [turn]
turn += 1
last_spoken = starting
for t in range(turn, TARGET):
last = nums[last_spoken]
n = last[1] - last[0] if len(last) == 2 else 0
nums[n] = nums[n][-1:] + [t]
last_spoken = n
last_spoken = get_target(line, 2020)
print("->", last_spoken)

View File

@@ -1,22 +1,10 @@
#!/usr/bin/env python3
from collections import defaultdict
from day15.common import get_target
lines = (x.strip() for x in open("input.txt"))
TARGET = 30000000
for line in lines:
print(line)
nums = defaultdict(list)
turn = 0
last_spoken = 0
for starting in map(int, line.split(",")):
nums[starting] = [turn]
turn += 1
last_spoken = starting
for t in range(turn, TARGET):
last = nums[last_spoken]
n = last[1] - last[0] if len(last) == 2 else 0
nums[n] = nums[n][-1:] + [t]
last_spoken = n
last_spoken = get_target(line, 30000000)
print("->", last_spoken)