executed multiple runs, incrementing the code address at which the instruction would be changed each run. Later halved the number of runs by starting at the maximum address, and decrementing that each run.
I could reduce it further by checking the selected address is nop or jmp, but can't be bothered
******
def resetProgram():
global addr
global acc
global program
addr = 0
acc = 0
for index, code in enumerate (program):
program [index][2] = 0
input_file = open("8aInput.txt", "r")
#input_as_list = [(line.strip()).split() for line in input_file]
input_as_list = [line.strip() for line in input_file]
input_file.close()
program = []
#parse input into program memory - third item of line is instruction execution count
for line in input_as_list:
codeLine = []
codeLine = [line.split(" ")[0],int(line.split(" ")[1]), 0]
program.append (codeLine)
addr = 0
acc = 0
addrToChange = len(program) - 1
runcount = 0
#Execute program
while addr < len(program):
# setup instruction
inst = program[addr][0]
if addr == addrToChange:
if inst == "nop" :
inst = "jmp"
print ("address ",addr, "nop changed to jmp")
elif inst == "jmp" :
inst = "nop"
print ("address ",addr, "jmp changed to nop")
param = program[addr][1]
#check for pass termination or execute instruction
program[addr][2]+=1
if program[addr][2] > 1:
print (acc, runcount, addrToChange)
resetProgram()
runcount +=1
addrToChange -=1
else:
#execute instruction
if inst == "jmp": addr+= param
elif inst == "acc":
acc+= param
addr+=1
else:
addr+=1
print (acc)