diff --git a/2021-python/solutions/day_02.py b/2021-python/solutions/day_02.py new file mode 100644 index 0000000..ab3c278 --- /dev/null +++ b/2021-python/solutions/day_02.py @@ -0,0 +1,38 @@ +from solutions import BaseSolution + + +class Solution(BaseSolution): + input_file = "02.txt" + + def __str__(self): + return "Day 2: Drive!" + + def parse_input(self, data): + def xy(direction, value): + if direction == "forward": + return (0, int(value)) + elif direction == "up": + return (-int(value), 0) + elif direction == "down": + return (int(value), 0) + + return [xy(*l.split()) for l in data.strip().splitlines()] + + def solve(self, puzzle_input): + x = sum(map(lambda xy: xy[0], puzzle_input)) + y = sum(map(lambda xy: xy[1], puzzle_input)) + return x * y + + def solve_again(self, puzzle_input): + pos = (0, 0, 0) + for x, y in puzzle_input: + if y > 0: + pos = (pos[2] * y + pos[0], pos[1] + y, pos[2]) + else: + pos = (pos[0], pos[1], pos[2] + x) + return pos[0] * pos[1] + + +if __name__ == "__main__": + solution = Solution() + solution.show_results() diff --git a/2021-python/tests/test_day_02.py b/2021-python/tests/test_day_02.py new file mode 100644 index 0000000..da826c6 --- /dev/null +++ b/2021-python/tests/test_day_02.py @@ -0,0 +1,36 @@ +import unittest + +from solutions.day_02 import Solution + + +class Day02TestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + self.puzzle_input = self.solution.parse_input( + """ + forward 5 +down 5 +forward 8 +up 3 +down 8 +forward 2 + """ + ) + + def test_parse_puzzle_input(self): + data = """ + forward 8 +up 3 +down 8 + """ + assert self.solution.parse_input(data) == [(0, 8), (-3, 0), (8, 0)] + + def test_solve_first_part(self): + assert self.solution.solve(self.puzzle_input) == 150 + + def test_solve_second_part(self): + assert self.solution.solve_again(self.puzzle_input) == 900 + + +if __name__ == "__main__": + unittest.main()