Solve 2021:7 "The Treachery of Whales"

This commit is contained in:
Anders Englöf Ytterström 2021-12-07 06:22:40 +01:00 committed by Anders Ytterström
parent bfe94864e9
commit 69c4518f29
2 changed files with 65 additions and 0 deletions

View file

@ -0,0 +1,36 @@
from solutions import BaseSolution
class Solution(BaseSolution):
input_file = "07.txt"
def __str__(self):
return "Day 7: The Treachery of Whales"
def parse_input(self, data):
return [int(d) for d in data.strip().split(",")]
def solve(self, puzzle_input):
return min(
[
sum(abs(start - pos) for start in puzzle_input)
for pos in range(max(puzzle_input))
]
)
def solve_again(self, puzzle_input):
l = sum(range(max(puzzle_input))) * len(puzzle_input)
for pos in range(max(puzzle_input)):
l = min(
l,
sum(
abs(start - pos) + sum(range(abs(start - pos)))
for start in puzzle_input
),
)
return l
if __name__ == "__main__":
solution = Solution()
solution.show_results()

View file

@ -0,0 +1,29 @@
import unittest
from solutions.day_07 import Solution
class Day07TestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
self.puzzle_input = self.solution.parse_input(
"""
16,1,2,0,4,2,7,1,2,14
"""
)
def test_parse_puzzle_input(self):
data = """
16,1,2
"""
assert self.solution.parse_input(data) == [16, 1, 2]
def test_solve_first_part(self):
assert self.solution.solve(self.puzzle_input) == 37
def test_solve_second_part(self):
assert self.solution.solve_again(self.puzzle_input) == 168
if __name__ == "__main__":
unittest.main()