From dd0709005644a778ee3212f8b44d8804eac7c936 Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Thu, 19 Dec 2024 22:35:55 +0100 Subject: [PATCH] Poor man's trie --- 2024/src/aoc/days/day19.py | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/2024/src/aoc/days/day19.py b/2024/src/aoc/days/day19.py index 328595e..53f239f 100644 --- a/2024/src/aoc/days/day19.py +++ b/2024/src/aoc/days/day19.py @@ -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 @@ def run_both(cls, input: str) -> int: 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: