StyleInCode

RSS

 

Day 8 - Advent of Code 2024

8 December 2024

Working solutions for the day 8 puzzles.

Part One

""" day_08_01.py """

# usage: python3 day_08_01.py < input

import sys


def on_grid(pos, across, down):
    """ pos within across by down """
    return pos[0] in range(across) and pos[1] in range(down)


def find_nodes(mast_1, mast_2):
    """ two antinodes per puzzle description """
    dy, dx = mast_1[1] - mast_2[1], mast_1[0] - mast_2[0]
    return [(mast_1[0] + dx, mast_1[1] + dy), (mast_2[0] - dx, mast_2[1] - dy)]


breakdown = {}
width, height = None, None
with sys.stdin as infile:
    for j, line in enumerate(infile):
        for i, obj in enumerate(line.strip()):
            if obj != '.':
                breakdown.setdefault(obj, []).append((i, j))
            width = i + 1
        height = j + 1

antinodes = []
for frequency, locations in breakdown.items():
    for m1, m2 in ((p, q) for i, p in enumerate(locations[:-1])
                   for q in locations[i + 1:]):
        antinodes.extend(find_nodes(m1, m2))

antinodes = {loc for loc in antinodes if on_grid(loc, width, height)}

print(len(antinodes))

Part Two

""" day_08_02.py """

# usage: python3 day_08_02.py < input

import sys


def on_grid(pos, across, down):
    """ pos within across by down """
    return pos[0] in range(across) and pos[1] in range(down)


def find_nodes(mast_1, mast_2, across, down):
    """ all antinodes per puzzle description """
    dy, dx = mast_1[1] - mast_2[1], mast_1[0] - mast_2[0]
    nodes = []
    k = 0
    p = mast_1
    while on_grid(p, across, down):
        nodes.append(p)
        k += 1
        p = (mast_1[0] + k * dx, mast_1[1] + k * dy)
    k = 0
    p = mast_2
    while on_grid(p, across, down):
        nodes.append(p)
        k += 1
        p = (mast_2[0] - k * dx, mast_2[1] - k * dy)
    return nodes


breakdown = {}
width, height = None, None
with sys.stdin as infile:
    for j, line in enumerate(infile):
        for i, obj in enumerate(line.strip()):
            if obj != '.':
                breakdown.setdefault(obj, []).append((i, j))
            width = i + 1
        height = j + 1

antinodes = []
for frequency, locations in breakdown.items():
    for m1, m2 in ((p, q) for i, p in enumerate(locations[:-1])
                   for q in locations[i + 1:]):
        antinodes.extend(find_nodes(m1, m2, width, height))

print(len(set(antinodes)))

Categories

Links