StyleInCode

RSS

 

Day 8 - Advent of Code 2025

8 December 2025

Working solutions for the day 8 puzzles.

Part One

""" day_08_01.py """

# usage: python3 day_08_01.py 1000 < input

import math
import sys


def d(box1, box2):
    """ distance between box1 and box2 """
    x1, y1, z1 = box1
    x2, y2, z2 = box2

    return round(math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2), 2)


n_closest = int(sys.argv[1])

with sys.stdin as infile:
    boxes = [tuple(map(int, line.strip().split(','))) for line in infile]

combos = [((b1, b2), d(b1, b2))
          for i, b1 in enumerate(boxes[:-1]) for b2 in boxes[i + 1:]]

combos.sort(key=lambda x: x[1])

cache = {}
circuits = {}
index = 0
for (b1, b2), _ in combos[:n_closest]:
    cs = (cache.get(b1, -1), cache.get(b2, -1))
    c1 = max(cs)
    if c1 == -1:
        circuits[index] = {b1, b2}
        cache[b1] = index
        cache[b2] = index
        index += 1
    else:
        circuits[c1] |= {b1, b2}
        cache[b1] = c1
        cache[b2] = c1
        c0 = min(cs)
        if c0 > -1 and c0 != c1:
            circuits[c1] |= circuits[c0]
            circuits[c0] = set()
            for i in circuits[c1]:
                cache[i] = c1

n = [len(boxes) for _, boxes in circuits.items()]
n.sort()

total = math.prod(n[-3:])
print(total)

Part Two

""" day_08_02.py """

# usage: python3 day_08_02.py < input

import math
import sys


def d(box1, box2):
    """ distance between box1 and box2 """
    x1, y1, z1 = box1
    x2, y2, z2 = box2

    return round(math.sqrt((x1 - x2)**2 + (y1 - y2)**2 + (z1 - z2)**2), 2)


with sys.stdin as infile:
    boxes = [tuple(map(int, line.strip().split(','))) for line in infile]

combos = [((b1, b2), d(b1, b2))
          for i, b1 in enumerate(boxes[:-1]) for b2 in boxes[i + 1:]]

combos.sort(key=lambda x: x[1])

combo = iter(combos)
cache = {}
circuits = {}
index = 0
while not (len(circuits) == 1 and len(cache) == len(boxes)):
    (b1, b2), _ = next(combo)
    cs = (cache.get(b1, -1), cache.get(b2, -1))
    c1 = max(cs)
    if c1 == -1:
        circuits[index] = {b1, b2}
        cache[b1] = index
        cache[b2] = index
        index += 1
    else:
        circuits[c1] |= {b1, b2}
        cache[b1] = c1
        cache[b2] = c1
        c0 = min(cs)
        if c0 > -1 and c0 != c1:
            circuits[c1] |= circuits[c0]
            del circuits[c0]
            for i in circuits[c1]:
                cache[i] = c1

total = b1[0] * b2[0]
print(total)

Categories

Links