|
| 1 | +""" |
| 2 | +Advent of Code 2024, Day 1: Historian Hysteria. |
| 3 | +
|
| 4 | +See: https://adventofcode.com/2024/day/1 |
| 5 | +""" |
| 6 | + |
| 7 | +import sys |
| 8 | +from collections import defaultdict |
| 9 | +from typing import TextIO |
| 10 | + |
| 11 | + |
| 12 | +def part_one(file: TextIO) -> int: |
| 13 | + """ |
| 14 | + Solve part one of the puzzle. |
| 15 | + """ |
| 16 | + left, right = [], [] |
| 17 | + for line in file.readlines(): |
| 18 | + a, b = line.split(maxsplit=1) |
| 19 | + left.append(int(a)) |
| 20 | + right.append(int(b)) |
| 21 | + |
| 22 | + left, right = sorted(left), sorted(right) |
| 23 | + |
| 24 | + return sum(map(lambda n: abs(n[0] - n[1]), zip(left, right))) |
| 25 | + |
| 26 | + |
| 27 | +def part_two(file: TextIO) -> int: |
| 28 | + """ |
| 29 | + Solve part two of the puzzle. |
| 30 | + """ |
| 31 | + left, right = [], defaultdict(lambda: 0) |
| 32 | + |
| 33 | + for line in file.readlines(): |
| 34 | + a, b = line.split(maxsplit=1) |
| 35 | + left.append(int(a)) |
| 36 | + right[int(b)] += 1 |
| 37 | + |
| 38 | + return sum(map(lambda n: n * right[n], left)) |
| 39 | + |
| 40 | + |
| 41 | +def main(): |
| 42 | + """ |
| 43 | + The main entrypoint for the script. |
| 44 | + """ |
| 45 | + filename = sys.argv[0].replace(".py", ".txt") |
| 46 | + |
| 47 | + with open(filename, encoding="utf-8") as file: |
| 48 | + print("Part one:", part_one(file)) |
| 49 | + |
| 50 | + with open(filename, encoding="utf-8") as file: |
| 51 | + print("Part two:", part_two(file)) |
| 52 | + |
| 53 | + |
| 54 | +if __name__ == "__main__": |
| 55 | + main() |
0 commit comments