diff --git a/day15/common.py b/day15/common.py new file mode 100644 index 0000000..a42b0a6 --- /dev/null +++ b/day15/common.py @@ -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)) diff --git a/day15/part1.py b/day15/part1.py index ff94a54..5633b79 100644 --- a/day15/part1.py +++ b/day15/part1.py @@ -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) diff --git a/day15/part2.py b/day15/part2.py index 1acd8a7..62ec9f3 100644 --- a/day15/part2.py +++ b/day15/part2.py @@ -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)