Skip to content

Commit dd07090

Browse files
committed
Poor man's trie
1 parent 891a5ea commit dd07090

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

2024/src/aoc/days/day19.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,37 @@
1+
import collections
12
import functools
23

34
from . import CombinedRunner
45

56

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

9-
return tuple(patterns.split(", ")), designs.split("\n")
10+
return patterns.split(", "), designs.split("\n")
1011

1112

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

18+
by_prefix = collections.defaultdict(list)
19+
for prefix in patterns:
20+
by_prefix[prefix[0]].append(prefix)
21+
1722
possible = 0
1823
ways = 0
1924

2025
@functools.cache
2126
def is_possible(design: str) -> bool:
2227
if not design:
2328
return 1
24-
25-
return sum(
26-
is_possible(design[len(pat) :])
27-
for pat in patterns
28-
if design.startswith(pat)
29-
)
29+
else:
30+
return sum(
31+
is_possible(design[len(prefix) :])
32+
for prefix in by_prefix[design[0]]
33+
if design.startswith(prefix)
34+
)
3035

3136
for design in designs:
3237
if (solve := is_possible(design)) > 0:

0 commit comments

Comments
 (0)