From ae922c5c33f868cbf2e63ab91b9d53e984acbb44 Mon Sep 17 00:00:00 2001 From: Nettika Date: Sun, 1 Dec 2024 20:34:04 -0800 Subject: [PATCH] Implement day 1 solver --- puzzles/1.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 puzzles/1.py diff --git a/puzzles/1.py b/puzzles/1.py new file mode 100644 index 0000000..7cecb4b --- /dev/null +++ b/puzzles/1.py @@ -0,0 +1,33 @@ +from collections import Counter + +test_input = """ +3 4 +4 3 +2 5 +1 3 +3 9 +3 3 +""".strip() + +test_solution_p1 = 11 +test_solution_p2 = 31 + + +def solve_p1(puzzle_input: str) -> int: + list1, list2 = _parse_lists(puzzle_input) + pairs = zip(sorted(list1), sorted(list2)) + distances = (abs(pair[0] - pair[1]) for pair in pairs) + return sum(distances) + + +def solve_p2(puzzle_input: str) -> int: + list1, list2 = _parse_lists(puzzle_input) + occurrences = Counter(list2) + similarities = (value * occurrences.get(value, 0) for value in list1) + return sum(similarities) + + +def _parse_lists(puzzle_input: str) -> tuple[list[int], list[int]]: + lines = (line.partition(" ") for line in puzzle_input.split("\n") if line) + list1, list2 = zip(*((int(line[0]), int(line[2])) for line in lines)) + return list1, list2