Day 12 - Advent of Code 2023

Working solutions for the day 12 puzzles.

Part One

""" day_12_01.py """

# usage: python3 day_12_01.py < input

import itertools
import sys


def valid_condition_record(record, groups):
    """ does record have the correct groups """
    tallys = []
    tally = 0
    for item in record + '.':
        if item == '#':
            tally += 1
        else:
            if tally > 0:
                tallys.append(tally)
                tally = 0
    return groups == ','.join(map(str, tallys))


records = []
with sys.stdin as input_text:
    for line in input_text:
        records.append(line.split())

count = 0
for condition, check in records:
    for i in itertools.product('.#', repeat=condition.count('?')):
        sample = list(i)
        springs = condition
        while sample:
            springs = springs.replace('?', sample.pop(), 1)
        if valid_condition_record(springs, check):
            count += 1

print(count)

Part Two