From 080e4e74ec84f78e13e8723ac1c1d6a49b1df801 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Thu, 19 Dec 2024 00:11:14 -0500 Subject: [PATCH] 2024: d19: ex2: add solution --- 2024/d19/ex2/ex2.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100755 2024/d19/ex2/ex2.py diff --git a/2024/d19/ex2/ex2.py b/2024/d19/ex2/ex2.py new file mode 100755 index 0000000..e7967bb --- /dev/null +++ b/2024/d19/ex2/ex2.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python + +import functools +import sys + + +def solve(input: str) -> int: + def parse(input: str) -> tuple[frozenset[str], list[str]]: + towels, patterns = input.split("\n\n") + return frozenset(towels.split(", ")), patterns.splitlines() + + @functools.cache + def count_ways(pattern: str, towels: frozenset[str]) -> int: + if pattern == "": + return 1 + return sum( + count_ways(pattern.removeprefix(towel), towels) + for towel in towels + if pattern.startswith(towel) + ) + + towels, patterns = parse(input) + return sum(count_ways(pattern, towels) for pattern in patterns) + + +def main() -> None: + input = sys.stdin.read() + print(solve(input)) + + +if __name__ == "__main__": + main()