Solve 2015:9 "All in a Single Night"

This commit is contained in:
Anders Englöf Ytterström 2023-10-25 23:24:51 +02:00
parent 5aba2fbed8
commit 8f5d73b4bf
3 changed files with 85 additions and 29 deletions

View file

@ -0,0 +1,54 @@
from itertools import permutations
from re import findall
from solutions import BaseSolution
class Solution(BaseSolution):
input_file = "09.txt"
def __str__(self):
return "Day 9: All in a Single Night"
def parse_input(self, data):
def fromtodest(line):
f, t, d = findall(r"(\w+) to (\w+) = (\d+)", line)[0]
return f, t, int(d)
return [fromtodest(line) for line in data.strip().splitlines()]
def solve(self, puzzle_input):
return min(self._distances(puzzle_input))
def solve_again(self, puzzle_input):
return max(self._distances(puzzle_input))
def _distances(self, puzzle_input):
places = set(
list(map(lambda sdd: sdd[0], puzzle_input))
+ list(map(lambda ssd: ssd[1], puzzle_input))
)
route_len = len(places)
return [
sum(
sum(
map(
lambda ssd: ssd[2],
filter(
lambda ssd: (
(ssd[0] == route[i] and ssd[1] == route[i + 1])
or (ssd[0] == route[i + 1] and ssd[1] == route[i])
),
puzzle_input,
),
)
)
for i in range(route_len - 1)
)
for route in permutations(places)
]
if __name__ == "__main__":
solution = Solution()
solution.show_results()

View file

@ -1,29 +0,0 @@
import unittest
from solutions.day_06 import Solution
class Day06TestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
self.puzzle_input = self.solution.parse_input(
"""
<REPLACE ME>
"""
)
def test_parse_puzzle_input(self):
data = """
<REPLACE ME>
"""
assert self.solution.parse_input(data) == "<REPLACE ME>"
# def test_solve_first_part(self):
# assert self.solution.solve(self.puzzle_input) == True
# def test_solve_second_part(self):
# assert self.solution.solve_again(self.puzzle_input) == True
if __name__ == "__main__":
unittest.main()

View file

@ -0,0 +1,31 @@
import unittest
from solutions.day_09 import Solution
class Day09TestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
self.puzzle_input = self.solution.parse_input(
"""
London to Dublin = 464
London to Belfast = 518
Dublin to Belfast = 141
"""
)
def test_parse_puzzle_input(self):
data = """
Lnd to Dbn = 123
"""
assert self.solution.parse_input(data) == [("Lnd", "Dbn", 123)]
def test_solve_first_part(self):
assert self.solution.solve(self.puzzle_input) == 605
def test_solve_second_part(self):
assert self.solution.solve_again(self.puzzle_input) == 982
if __name__ == "__main__":
unittest.main()