diff --git a/2021-python/solutions/day_07.py b/2021-python/solutions/day_07.py new file mode 100644 index 0000000..a97d12e --- /dev/null +++ b/2021-python/solutions/day_07.py @@ -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() diff --git a/2021-python/tests/test_day_07.py b/2021-python/tests/test_day_07.py new file mode 100644 index 0000000..fe6c31b --- /dev/null +++ b/2021-python/tests/test_day_07.py @@ -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()