Skip to content

Commit

Permalink
Poor man's trie
Browse files Browse the repository at this point in the history
  • Loading branch information
bertptrs committed Dec 19, 2024
1 parent 891a5ea commit dd07090
Showing 1 changed file with 13 additions and 8 deletions.
21 changes: 13 additions & 8 deletions 2024/src/aoc/days/day19.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
import collections
import functools

from . import CombinedRunner


def parse_input(data: str) -> tuple[tuple[str, ...], list[str]]:
def parse_input(data: str) -> tuple[list[str], list[str]]:
patterns, designs = data.strip().split("\n\n")

return tuple(patterns.split(", ")), designs.split("\n")
return patterns.split(", "), designs.split("\n")


class DayRunner(CombinedRunner):
@classmethod
def run_both(cls, input: str) -> int:
patterns, designs = parse_input(input)

by_prefix = collections.defaultdict(list)
for prefix in patterns:
by_prefix[prefix[0]].append(prefix)

possible = 0
ways = 0

@functools.cache
def is_possible(design: str) -> bool:
if not design:
return 1

return sum(
is_possible(design[len(pat) :])
for pat in patterns
if design.startswith(pat)
)
else:
return sum(
is_possible(design[len(prefix) :])
for prefix in by_prefix[design[0]]
if design.startswith(prefix)
)

for design in designs:
if (solve := is_possible(design)) > 0:
Expand Down

0 comments on commit dd07090

Please sign in to comment.