|
| 1 | +from collections import Counter |
| 2 | + |
| 3 | +from adventofcode.registry.decorators import register_solution |
| 4 | +from adventofcode.util.exceptions import SolutionNotFoundError |
| 5 | +from adventofcode.util.input_helpers import get_input_for_day |
| 6 | + |
| 7 | + |
| 8 | +def parse_input(input_data: list[str]) -> tuple[list, list]: |
| 9 | + left_list: list[int] = [] |
| 10 | + right_list: list[int] = [] |
| 11 | + |
| 12 | + for row in input_data: |
| 13 | + left, right = row.split(" ") |
| 14 | + left_list.append(int(left)) |
| 15 | + right_list.append(int(right)) |
| 16 | + |
| 17 | + return sorted(left_list), sorted(right_list) |
| 18 | + |
| 19 | + |
| 20 | +def calculate_distances(data: tuple[list[int], list[int]]) -> int: |
| 21 | + total = 0 |
| 22 | + for left, right in zip(*data, strict=True): |
| 23 | + total += abs(left - right) |
| 24 | + |
| 25 | + return total |
| 26 | + |
| 27 | + |
| 28 | +def calculate_similarity(data: tuple[list[int], list[int]]) -> int: |
| 29 | + total = 0 |
| 30 | + left_list, right_list = data |
| 31 | + right_counter = Counter(right_list) |
| 32 | + |
| 33 | + for num in left_list: |
| 34 | + total += right_counter[num] * num |
| 35 | + |
| 36 | + return total |
| 37 | + |
| 38 | + |
| 39 | +@register_solution(2024, 1, 1) |
| 40 | +def part_one(input_data: list[str]): |
| 41 | + parsed_input = parse_input(input_data) |
| 42 | + answer = calculate_distances(parsed_input) |
| 43 | + |
| 44 | + if not answer: |
| 45 | + raise SolutionNotFoundError(2024, 1, 1) |
| 46 | + |
| 47 | + return answer |
| 48 | + |
| 49 | + |
| 50 | +@register_solution(2024, 1, 2) |
| 51 | +def part_two(input_data: list[str]): |
| 52 | + parsed_input = parse_input(input_data) |
| 53 | + answer = calculate_similarity(parsed_input) |
| 54 | + |
| 55 | + if not answer: |
| 56 | + raise SolutionNotFoundError(2024, 1, 2) |
| 57 | + |
| 58 | + return answer |
| 59 | + |
| 60 | + |
| 61 | +if __name__ == "__main__": |
| 62 | + data = get_input_for_day(2024, 1) |
| 63 | + part_one(data) |
| 64 | + part_two(data) |
0 commit comments