Advertisement
TwoShedsDerrick

AoC Day 21

Dec 21st, 2022 (edited)
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.80 KB | None | 0 0
  1. import pathlib
  2. import operator
  3.  
  4. ops = {'+': operator.add, '-': operator.sub, '*': operator.mul, '/': operator.floordiv}
  5.  
  6. with pathlib.Path("day21.txt").open('r') as f:
  7.     known, known2, unknown = {}, {}, []
  8.     for k, v in (l.strip().split(": ", 1) for l in f.readlines()):
  9.         if len(bits := v.split(' ')) == 1:
  10.             known2[k] = known[k] = int(v)
  11.         else:
  12.             unknown.append((k, bits[0], ops[bits[1]], bits[2]))
  13.  
  14. while unknown:
  15.     for _ in range(len(unknown)):
  16.         k, m1, op, m2 = r = unknown.pop(0)
  17.         if m1 not in known or m2 not in known:
  18.             unknown.append(r)
  19.             continue
  20.  
  21.         known[k] = int(op(known[m1], known[m2]))
  22.  
  23.         if k == 'root':
  24.             known2[k] = (known2[m1], known2[m2])
  25.         elif 'humn' not in (m1, m2) and isinstance(known2[m1], int) and isinstance(known2[m2], int):
  26.             known2[k] = known[k]
  27.         else:
  28.           known2[k] = (op, 'x' if m1 == 'humn' else known2[m1], 'x' if m2 == 'humn' else known2[m2])
  29.  
  30. print(known['root'])
  31.  
  32. l, r = known2['root']
  33. if isinstance(r, int): # one of l and r is literal - make sure it is l
  34.     t = r; r = l; l = t # swap r and l
  35.  
  36. while r: # reverse the equation to solve for x
  37.     if r == 'x': break # we're done!
  38.     fn, a, b = r
  39.     r = a if isinstance(b, int) else b # keep expanding into which ever of a and b is a tuple
  40.     # rearrange the current level of the equation to put the tuple on the right
  41.     if fn == operator.floordiv: # l = a / b
  42.         l = l*b if isinstance(b, int) else a / l
  43.     elif fn == operator.mul: # l = a * b
  44.         l = int(l / (a  if isinstance(a, int) else b))
  45.     elif fn == operator.sub: # l = a - b
  46.         l = a-l if isinstance(a, int) else l+b
  47.     else: # l = a + b
  48.         l = l - (a if isinstance(a, int) else b)
  49.  
  50. print(l)
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement