Advertisement
hhoppe

Advent of code 2023 day 19 part2 old

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