Skip to content
advent of code 2023

day 03

gear ratios

approach

numbers are found row by row with a regex, and each becomes a Node with its value, its column span and its row. a node's vicinity is every cell around its span, minus the span itself.

part 1 sums the numbers that have any symbol in their vicinity. part 2 only looks for *: each number touching a star is grouped under that star's position, and stars with more than one number contribute the product of their numbers. the code assumes a number never touches more than one symbol.

the trick

group numbers by the star they touch; gears are the groups with more than one entry.

python
def part2(grid, nodes):
    symbols = '*'
    groups = defaultdict(list)
    for node in nodes:
        if (adj := node.is_symbol_adjacent(grid, symbols)) is not None:
            groups[adj].append(node.val)
    return sum(prod(l) for l in groups.values() if len(l) > 1)