Advertisement
Guest User

Untitled

a guest
Dec 2nd, 2019
1,349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. from z3 import And, Array, If, Int, IntSort, Or, Solver, Store
  2.  
  3. codes = open("inputs/2.txt").read().strip().split(",")
  4. codes = list(map(int, codes))
  5. N = len(codes)
  6.  
  7. s = Solver()
  8.  
  9. # Initialize array replacing position 1 and 2 with variables a and b
  10. A = Array("A", IntSort(), IntSort())
  11. a = Int("a")
  12. b = Int("b")
  13. for i, c in enumerate(codes):
  14.     if i == 1:
  15.         A = Store(A, i, a)
  16.     elif i == 2:
  17.         A = Store(A, i, b)
  18.     else:
  19.         A = Store(A, i, codes[i])
  20. # As a hack we also store the instruction pointer at position N
  21. A = Store(A, N, 0)
  22.  
  23. # Each iteration calculates A at timestep t
  24. # Since A is both our instructions and instruction pointer, we can update both simultaneously
  25. for t in range(0, N, 4):
  26.     ip = A[N]
  27.     # Check if it's a valid op
  28.     op = A[ip]
  29.     s.add(Or(op == 1, op == 2, op == 99))
  30.     # If not stopped, the indices also have to be valid
  31.     stopped = op == 99
  32.     validIndices = And(
  33.         A[ip + 1] >= 0,
  34.         A[ip + 1] < N,
  35.         A[ip + 2] >= 0,
  36.         A[ip + 2] < N,
  37.         A[ip + 3] >= 0,
  38.         A[ip + 3] < N,
  39.     )
  40.     s.add(Or(stopped, validIndices))
  41.     # Update A with the new A that has A[N] += 4 and the result of the op
  42.     # If op is not 1 or 2, the new A is just the old A (where instruction pointer isn't incremented either)
  43.     A = If(
  44.         op == 1,
  45.         Store(Store(A, N, ip + 4), A[ip + 3], A[A[ip + 1]] + A[A[ip + 2]]),
  46.         If(
  47.             op == 2,
  48.             Store(Store(A, N, ip + 4), A[ip + 3], A[A[ip + 1]] * A[A[ip + 2]]),
  49.             # else no-op
  50.             A,
  51.         ),
  52.     )
  53.  
  54. s.add(A[A[N]] == 99)  # Program is stopped
  55. s.add(A[0] == 19690720)  # The desired target value
  56.  
  57. print("isSat", s.check())
  58. m = s.model()
  59. print("model", m)
  60. a_long = m[a].as_long()
  61. b_long = m[b].as_long()
  62. print("a", a_long)
  63. print("b", b_long)
  64. print("Part 2", 100 * a_long + b_long)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement