Solve 2015:14 "Reindeer Olympics"

This commit is contained in:
Anders Englöf Ytterström 2023-10-26 18:25:07 +02:00
parent e859324030
commit cfd2c0f079
2 changed files with 79 additions and 0 deletions

View file

@ -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()

View file

@ -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()