Advertisement
hhoppe

Advent of code 2023 day 19 part2 improved

Dec 19th, 2023 (edited)
1,120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. def day19_part2(s):
  2.   s_rules, _ = s.split('\n\n')
  3.   rules = {}
  4.   for line in s_rules.splitlines():
  5.     name, s_rules = line[:-1].split('{')
  6.     rules[name] = s_rules.split(',')
  7.  
  8.   def compute(name, intervals):
  9.     if name == 'R' or any(start >= stop for start, stop in intervals.values()):
  10.       return 0
  11.     if name == 'A':
  12.       return math.prod(stop - start for start, stop in intervals.values())
  13.  
  14.     total = 0
  15.     for rule in rules[name]:
  16.       if rule.isalpha():
  17.         return total + compute(rule, intervals)
  18.  
  19.       category, op, s_num, label = re.match(r'^(\w)([<>])(\d+):(\w+)$', rule).groups()
  20.       num = int(s_num)
  21.       start, stop = intervals[category]
  22.       if op == '<':
  23.         total += compute(label, intervals | {category: (start, min(stop, num))})
  24.         intervals[category] = max(start, num), stop
  25.       else:
  26.         total += compute(label, intervals | {category: (max(start, num + 1), stop)})
  27.         intervals[category] = start, min(stop, num + 1)
  28.  
  29.   return compute('in', {category: (1, 4001) for category in 'xmas'})
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement