Advertisement
hhoppe

Advent of code 2024 day 19

Dec 19th, 2024
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.12 KB | None | 0 0
  1. def day19(s, *, part2=False):  # Faster using 2-character prefix buckets.
  2.   p1, p2 = s.split('\n\n')
  3.   towels = p1.split(', ')
  4.   designs = p2.splitlines()
  5.  
  6.   towels_1ch = {towel for towel in towels if len(towel) == 1}
  7.   towels_2ch_prefix = collections.defaultdict(list)
  8.   for towel in towels:
  9.     if len(towel) >= 2:
  10.       towels_2ch_prefix[towel[:2]].append(towel)
  11.  
  12.   def is_possible(design):
  13.     if not design:
  14.       return True
  15.     if design[0] in towels_1ch and is_possible(design[1:]):
  16.       return True
  17.     for towel in towels_2ch_prefix[design[:2]]:
  18.       if design.startswith(towel) and is_possible(design[len(towel) :]):
  19.         return True
  20.     return False
  21.  
  22.   @functools.cache
  23.   def num_possible(design):
  24.     if not design:
  25.       return 1
  26.     count = 0
  27.     if design[0] in towels_1ch:
  28.       count += num_possible(design[1:])
  29.     for towel in towels_2ch_prefix[design[:2]]:
  30.       if design.startswith(towel):
  31.         count += num_possible(design[len(towel) :])
  32.     return count
  33.  
  34.   total = 0
  35.   for design in designs:
  36.     total += num_possible(design) if part2 else is_possible(design)
  37.  
  38.   return total
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement