From 9976edc457b08d94044d2319e4e801c28bf46b85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20Ytterstr=C3=B6m?= Date: Wed, 1 Dec 2021 06:38:45 +0100 Subject: [PATCH] Solve 2021:1 "Sonar sweep" Felt a bit slow and rusty. Tooling was not set up properly on the computer which decreased the flow. Anyhow, fun first day! Could have been done more pythonic with list sequences, and readability would have increased with more use of sum() and lambdas. But this is not what Advent of Code is about. --- 2021-python/solutions/day_01.py | 31 +++++++++++++++++++++++++ 2021-python/tests/test_day_01.py | 40 ++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 2021-python/solutions/day_01.py create mode 100644 2021-python/tests/test_day_01.py diff --git a/2021-python/solutions/day_01.py b/2021-python/solutions/day_01.py new file mode 100644 index 0000000..e181a5f --- /dev/null +++ b/2021-python/solutions/day_01.py @@ -0,0 +1,31 @@ +from solutions import BaseSolution + + +class Solution(BaseSolution): + input_file = "01.txt" + + def __str__(self): + return "Day 1: Sonar Sweep" + + def parse_input(self, data): + return [int(n) for n in data.split()] + + def solve(self, puzzle_input): + return sum( + [puzzle_input[i] > puzzle_input[i - 1] for i in range(1, len(puzzle_input))] + ) + + def solve_again(self, puzzle_input): + puzzle_input.append(max(puzzle_input) + 1) + return sum( + [ + (puzzle_input[i] + puzzle_input[i - 1] + puzzle_input[i - 2]) + > (puzzle_input[i - 1] + puzzle_input[i - 2] + puzzle_input[i - 3]) + for i in range(2, len(puzzle_input) - 1) + ] + ) + + +if __name__ == "__main__": + solution = Solution() + solution.show_results() diff --git a/2021-python/tests/test_day_01.py b/2021-python/tests/test_day_01.py new file mode 100644 index 0000000..5a9e9d9 --- /dev/null +++ b/2021-python/tests/test_day_01.py @@ -0,0 +1,40 @@ +import unittest + +from solutions.day_01 import Solution + + +class Day01TestCase(unittest.TestCase): + def setUp(self): + self.solution = Solution() + self.puzzle_input = self.solution.parse_input( + """ + 199 +200 +208 +210 +200 +207 +240 +269 +260 +263 + """ + ) + + def test_parse_puzzle_input(self): + data = """ + 12 + 23 + 45 + """ + assert self.solution.parse_input(data) == [12, 23, 45] + + def test_solve_first_part(self): + assert self.solution.solve(self.puzzle_input) == 7 + + def test_solve_second_part(self): + assert self.solution.solve_again(self.puzzle_input) == 5 + + +if __name__ == "__main__": + unittest.main()