mirror of
https://github.com/bertptrs/adventofcode.git
synced 2025-12-25 21:00:31 +01:00
Poor man's trie
This commit is contained in:
@@ -1,12 +1,13 @@
|
||||
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):
|
||||
@@ -14,6 +15,10 @@ class DayRunner(CombinedRunner):
|
||||
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
|
||||
|
||||
@@ -21,12 +26,12 @@ class DayRunner(CombinedRunner):
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user