File tree Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Expand file tree Collapse file tree 1 file changed +13
-8
lines changed Original file line number Diff line number Diff line change 1+ import collections
12import functools
23
34from . 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
1213class 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 :
You can’t perform that action at this time.
0 commit comments