From cfd2c0f079fb5ae9462fb405235b68cf99b88010 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Engl=C3=B6f=20Ytterstr=C3=B6m?= Date: Thu, 26 Oct 2023 18:25:07 +0200 Subject: [PATCH] Solve 2015:14 "Reindeer Olympics" --- 2015-python/solutions/day_14.py | 49 ++++++++++++++++++++++++++++++++ 2015-python/tests/test_day_14.py | 30 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 2015-python/solutions/day_14.py create mode 100644 2015-python/tests/test_day_14.py diff --git a/2015-python/solutions/day_14.py b/2015-python/solutions/day_14.py new file mode 100644 index 0000000..cffb9da --- /dev/null +++ b/2015-python/solutions/day_14.py @@ -0,0 +1,49 @@ +from collections import defaultdict +from re import compile, findall +from solutions import BaseSolution + + +class Solution(BaseSolution): + input_file = "14.txt" + + def __str__(self): + return "Day 14: Reindeer Olympics" + + def parse_input(self, data): + digits = compile(r"\d+") + return [ + tuple(map(int, findall(digits, line))) for line in data.strip().splitlines() + ] + + def solve(self, puzzle_input, checkin=2503): + reindeers = [] + for speed, duration, rest in puzzle_input: + window = duration + rest + sprints = checkin // window + if checkin % window >= duration: + sprints += 1 + reindeers.append(speed * duration * sprints) + return max(reindeers) + + def solve_again(self, puzzle_input, checkin=2503): + distances = defaultdict(int) + subwinners = defaultdict(int) + for ts in range(checkin): + r = 0 + longest_distance = 0 + for speed, duration, rest in puzzle_input: + if ts % (duration + rest) < duration: + distances[r] += speed + if distances[r] >= longest_distance: + longest_distance = distances[r] + r += 1 + + for r in [k for k, v in distances.items() if v == longest_distance]: + subwinners[r] += 1 + + return max(subwinners.values()) + + +if __name__ == "__main__": + solution = Solution() + solution.show_results() diff --git a/2015-python/tests/test_day_14.py b/2015-python/tests/test_day_14.py new file mode 100644 index 0000000..22f8eb4 --- /dev/null +++ b/2015-python/tests/test_day_14.py @@ -0,0 +1,30 @@ +import unittest + +from solutions.day_14 import Solution + + +class Day14TestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + self.puzzle_input = self.solution.parse_input( + """ + Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds. + Dancer can fly 16 km/s for 11 seconds, but then must rest for 162 seconds. + """ + ) + + def test_parse_puzzle_input(self): + data = """ + Comet can fly 14 km/s for 10 seconds, but then must rest for 127 seconds. + """ + assert self.solution.parse_input(data) == [(14, 10, 127)] + + def test_solve_first_part(self): + assert self.solution.solve(self.puzzle_input, 1000) == 1120 + + def test_solve_second_part(self): + assert self.solution.solve_again(self.puzzle_input, 1000) == 689 + + +if __name__ == "__main__": + unittest.main()