17_computer.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. #!/usr/bin/env python3
  2. import sys
  3. import re
  4. def run(program, regs):
  5. a, b, c = range(4, 7)
  6. ip = 0
  7. combo = [0, 1, 2, 3, *regs]
  8. while ip < len(program):
  9. opcode, operand = program[ip:ip + 2]
  10. if opcode == 0:
  11. combo[a] >>= combo[operand]
  12. elif opcode == 1:
  13. combo[b] ^= operand
  14. elif opcode == 2:
  15. combo[b] = combo[operand] % 8
  16. elif opcode == 3:
  17. if combo[a]:
  18. ip = operand - 2
  19. elif opcode == 4:
  20. combo[b] ^= combo[c]
  21. elif opcode == 5:
  22. yield combo[operand] % 8
  23. elif opcode == 6:
  24. combo[b] = combo[a] >> combo[operand]
  25. elif opcode == 7:
  26. combo[c] = combo[a] >> combo[operand]
  27. ip += 2
  28. def expect(program, out, prev_a=0):
  29. if not out:
  30. return prev_a
  31. for a in range(1 << 10):
  32. if a >> 3 == prev_a & 127 and next(run(program, (a, 0, 0))) == out[-1]:
  33. ret = expect(program, out[:-1], (prev_a << 3) | (a % 8))
  34. if ret is not None:
  35. return ret
  36. nums = list(map(int, re.findall(r'\d+', sys.stdin.read())))
  37. regs = nums[:3]
  38. program = nums[3:]
  39. print(','.join(map(str, run(program, regs))))
  40. print(expect(program, program))