You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.4KB

  1. import collections
  2. def program(qsnd, qrcv, known=tuple()):
  3. i, j = 0, 0
  4. regs = collections.defaultdict(int)
  5. regs.update(known)
  6. read = lambda value: regs[value] if value.isalpha() else int(value)
  7. while True:
  8. line = lines[i]
  9. op, *args = line.split()
  10. if op == 'set':
  11. x, y = args
  12. regs[x] = read(y)
  13. elif op == 'mul':
  14. x, y = args
  15. regs[x] *= read(y)
  16. elif op == 'jgz':
  17. x, y = args
  18. if read(x) > 0:
  19. i += read(y)
  20. continue
  21. elif op == 'add':
  22. x, y = args
  23. regs[x] += read(y)
  24. elif op == 'snd':
  25. x, = args
  26. qsnd.append(read(x))
  27. elif op == 'rcv':
  28. x, = args
  29. if not known:
  30. if read(x) != 0:
  31. yield False
  32. continue
  33. else:
  34. if j < len(qrcv):
  35. regs[x] = qrcv[j]
  36. j += 1
  37. else:
  38. yield False
  39. continue
  40. elif op == 'mod':
  41. x, y = args
  42. regs[x] %= read(y)
  43. i += 1
  44. yield True
  45. lines = df.read_text().splitlines()
  46. q = []
  47. p = program(q, None)
  48. while next(p): pass
  49. ans1 = q[-1]
  50. qA, qB = [], []
  51. p0 = program(qA, qB, {'p': 0})
  52. p1 = program(qB, qA, {'p': 1})
  53. while next(p0) + next(p1): pass
  54. ans2 = len(qB)