Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with open('in.txt', 'r') as f:
- data = [int(y) for x in f.readlines() for y in x.strip().split(',')]
- iptr, code = 0, data[:]
- add, mul, inp, out, hlt = 1, 2, 3, 4, 99
- pos, imm = 0, 1
- def get_input():
- return 1
- def next():
- global code, iptr
- val, iptr = code[iptr], iptr + 1
- return val
- def process_opcode(op):
- c = str(op)
- # If the opcode is a number 2 or less we can assume all modes are 0
- if len(c) <= 2:
- return int(c[-2:]), [0,0,0]
- # take the 3 first numbers and make a list then revese it
- return int(c[-2:]), ([0] * (5 - len(c)) + [int(x) for x in c])[:3][::-1]
- def peek(val, mode):
- global code
- return mode == imm and val or code[val]
- def poke(addr, val):
- global code
- code[addr] = val
- outs = []
- while True:
- op, modes = process_opcode(next())
- # We can handle these better
- if op == add or op == mul:
- lval = peek(next(), modes[0])
- rval = peek(next(), modes[1])
- if op == add:
- poke(next(), lval + rval)
- elif op == mul:
- poke(next(), lval * rval)
- else:
- if op == inp:
- # input always writes to an address
- poke(next(), get_input())
- elif op == out:
- outs.append(peek(next(), pos))
- elif op == hlt:
- print(outs)
- print("Exiting program.")
- break
- else:
- print("Unexpected operation. Aborting.")
- break
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement