StyleInCode

RSS

 

Day 10 - Advent of Code 2024

10 December 2024

Working solutions for the day 10 puzzles.

Part One

""" day_10_01.py """

# usage: python3 day_10_01.py < input

import sys


def height9(begin, across, down, net):
    """ 9-heights reached from begin """
    def xy(pos):
        """ x, y """
        return pos % across, pos // across

    def pos(x, y):
        """ pos """
        return x + y * across

    def on(x, y):
        """ on net """
        return x in range(across) and y in range(down)

    if net[begin] == 9:
        return [begin]

    deltas = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    path = []
    x, y = xy(begin)
    for dx, dy in deltas:
        if not on(x + dx, y + dy):
            continue
        if net[pos(x + dx, y + dy)] - net[begin] == 1:
            path.append(pos(x + dx, y + dy))

    result = []
    for p in path:
        result.extend(height9(p, across, down, net))
    return list(set(result))


width, height = None, None
grid = []
with sys.stdin as infile:
    for j, line in enumerate(infile):
        for i, alt in enumerate(line.strip()):
            grid.append(int(alt))
            width = i + 1
        height = j + 1

trailheads = [i for i, alt in enumerate(grid) if alt == 0]

print(sum(len(height9(head, width, height, grid)) for head in trailheads))

Part Two

""" day_10_02.py """

# usage: python3 day_10_02.py < input

import sys


def height9(begin, across, down, net):
    """ ways 9-heights reached from begin """
    def xy(pos):
        """ x, y """
        return pos % across, pos // across

    def pos(x, y):
        """ pos """
        return x + y * across

    def on(x, y):
        """ on net """
        return x in range(across) and y in range(down)

    if net[begin] == 9:
        return [begin]

    deltas = [(0, -1), (1, 0), (0, 1), (-1, 0)]
    path = []
    x, y = xy(begin)
    for dx, dy in deltas:
        if not on(x + dx, y + dy):
            continue
        if net[pos(x + dx, y + dy)] - net[begin] == 1:
            path.append(pos(x + dx, y + dy))

    result = []
    for p in path:
        result.extend(height9(p, across, down, net))
    return result


width, height = None, None
grid = []
with sys.stdin as infile:
    for j, line in enumerate(infile):
        for i, alt in enumerate(line.strip()):
            grid.append(int(alt))
            width = i + 1
        height = j + 1

trailheads = [i for i, alt in enumerate(grid) if alt == 0]

print(sum(len(height9(head, width, height, grid)) for head in trailheads))

Categories

Links