Advertisement
kupuguy

Advent Of Code 2024 Day 19

Dec 19th, 2024
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | Source Code | 0 0
  1. from pathlib import Path
  2. from functools import cache
  3.  
  4.  
  5. def parse(input: str) -> tuple[set[str], list[str]]:
  6.     lines = input.splitlines()
  7.     towels = [s.strip() for s in lines[0].split(",")]
  8.     return set(towels), lines[2:]
  9.  
  10.  
  11. def part1(towels: set[str], patterns: list[str]) -> int:
  12.     @cache
  13.     def can_solve(pattern: str) -> bool:
  14.         if not pattern:
  15.             return True
  16.         for i in range(1, len(pattern) + 1):
  17.             t = pattern[:i]
  18.             if t in towels and can_solve(pattern[i:]):
  19.                 return True
  20.         return False
  21.  
  22.     return sum(1 if can_solve(p) else 0 for p in patterns)
  23.  
  24.  
  25. TEST_TOWELS, TEST_PATTERNS = parse(Path("input/day19-test.txt").read_text())
  26. assert part1(TEST_TOWELS, TEST_PATTERNS) == 6
  27.  
  28. INPUT_TOWELS, INPUT_PATTERNS = parse(Path("input/day19.txt").read_text())
  29. part1_total = part1(INPUT_TOWELS, INPUT_PATTERNS)
  30. print(f"{part1_total=:,}")
  31.  
  32.  
  33. def part2(towels: set[str], patterns: list[str]) -> int:
  34.     longest_towel = max(len(t) for t in towels)
  35.  
  36.     @cache
  37.     def solve(pattern: str) -> int:
  38.         if not pattern:
  39.             return 1
  40.         solutions = 0
  41.         for i in range(1, min(longest_towel, len(pattern)) + 1):
  42.             t = pattern[:i]
  43.             if t in towels:
  44.                 solutions += solve(pattern[i:])
  45.         return solutions
  46.  
  47.     return sum(solve(p) for p in patterns)
  48.  
  49.  
  50. assert part2(TEST_TOWELS, TEST_PATTERNS) == 16
  51.  
  52. part2_total = part2(INPUT_TOWELS, INPUT_PATTERNS)
  53. print(f"{part2_total=:,}")  # 572,248,688,842,069
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement