Advertisement
icarussiano

day 19 part 2

Dec 19th, 2023 (edited)
684
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.44 KB | None | 0 0
  1. work, _ = open("input").read().split('\n\n')
  2. workflows = {name: rules[:-1].split(',') for name, rules in (line.split('{') for line in work.splitlines())}
  3.  
  4. def find_rules(current, rules):
  5.     if current == 'A':
  6.         regole.append(rules)
  7.     elif current != 'R':
  8.         rul = []
  9.         for rule in workflows[current][:-1]:
  10.             if rule not in 'AR':
  11.                 next_workflow = rule.split(':')[1]
  12.                 find_rules(next_workflow, rules + rul + [rule.split(':')[0]])
  13.                 if rule[1] == '<':
  14.                     rul.append(rule.split(':')[0].split('<')[0] + '>=' + rule.split(':')[0].split('<')[1])
  15.                 elif rule[1] == '>':
  16.                     rul.append(rule.split(':')[0].split('>')[0] + '<=' + rule.split(':')[0].split('>')[1])
  17.         else:
  18.             next_workflow = workflows[current][-1]
  19.             find_rules(next_workflow, rules + rul)
  20.  
  21. regole = []
  22. find_rules('in', [])
  23. somma = 0
  24. for r in regole:
  25.     maxs = {x: 4001 for x in 'xmas'}
  26.     mins = {x: 0 for x in 'xmas'}
  27.     for s in r:
  28.         if s[0] in 'xmas' and s[1] == '<':
  29.             maxs[s[0]] = min(maxs[s[0]], int(s[2:])) if s[2] != '=' else min(maxs[s[0]], int(s[3:]) + 1)
  30.         elif s[0] in 'xmas' and s[1] == '>':
  31.             mins[s[0]] = max(mins[s[0]], int(s[2:])) if s[2] != '=' else max(mins[s[0]], int(s[3:]) - 1)
  32.     p = 1
  33.     for key in maxs:
  34.         p *= (maxs[key] - mins[key] - 1)
  35.     somma += p
  36. print(somma)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement