Sean McLemon | Advent of Code

Home | Czech | Blog | GitHub | Advent Of Code | Notes


2024-12-01 - Historian Hysteria

(original .ipynb)

Day 1 puzzle input is a list of pairs of integers which represent some location identifiers (mine is here). Part 1 involves treating the list as two separate columns of data, sorting each and finding the sum of differences between each corresponding element of each column. Part two involves calculating a "similarity" score for each element of the left column (each value in the left column multiplied by how many occurrences of each value there are in the right column) and finding the sum of all similarity scores.

puzzle_input_str = open("./puzzle_input/day1.txt").read()
test_input_str = """3   4
4   3
2   5
1   3
3   9
3   3"""


def parse_line(line: str) -> int:
    left, right = line.split("   ")
    return (int(left), int(right))


def part_one(input_str: str) -> int:
    input_lines = input_str.splitlines()
    parsed_lines = [parse_line(line) for line in input_lines]
    sorted_input = zip(
        sorted((line[0] for line in parsed_lines)),
        sorted((line[1] for line in parsed_lines))
    )
    return sum(abs(left-right) for left, right in sorted_input)


assert 11 == part_one(test_input_str)

print("part one:", part_one(puzzle_input_str))
part one: 2176849
from collections import defaultdict
def part_two(input_str):
    lines = input_str.splitlines()
    parsed = [parse_line(line) for line in lines]
    lefts = [left for left, right in parsed]
    rights = defaultdict(lambda: 0)
    for line in parsed:
        rights[line[1]] += 1
    
    return sum(left * rights[left] for left in lefts)

assert 31 == part_two(test_input_str)

print("part two:", part_two(puzzle_input_str))
part two: 23384288