StyleInCode

RSS

 

Day 19 - Advent of Code 2024

19 December 2024

Working solutions for the day 19 puzzles.

Part One

""" day_19_01.py """

# usage: python3 day_19_01.py < input

import sys


cache = set()


def verify(design, templates):
    """ can design be assembled from templates """
    if design in cache or design == '':
        return True

    for i in [len(t) for t in templates if design.startswith(t)]:
        if verify(design[i:], templates):
            cache.add(design[i:])
            return True

    return False


with sys.stdin as infile:
    patterns = input().split(', ')
    input()
    valid = sum(1 for proposed in infile if verify(proposed.strip(), patterns))

print(valid)

Part Two

""" day_19_02.py """

# usage: python3 day_19_02.py < input

import sys


cache = {}


def count(design, templates):
    """ how many ways can design be assembled from templates """
    if design in cache:
        return cache[design]

    if design == '':
        return 1

    num = 0
    for i in [len(t) for t in templates if design.startswith(t)]:
        partial = cache.setdefault(design[i:], count(design[i:], templates))
        num += partial

    return num


with sys.stdin as infile:
    patterns = input().split(', ')
    input()
    total = sum(count(proposed.strip(), patterns) for proposed in infile)

print(total)

Categories

Links