Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program = []
- with open("8 - input", 'r') as file:
- lines = file.readlines()
- for line in lines:
- line = line.strip("\n")
- program.append([line.split(" ")[0], line.split(" ")[1][0], int(line.split(" ")[1][1:])])
- def execute(index, instruction, acc, printLog=False):
- spacer = "\t"
- if index < 10:
- spacer = spacer * 2
- if instruction[0] == "nop":
- if printLog:
- print(f"[{index}]{spacer}{instruction[0]}")
- return index + 1, acc
- elif instruction[0] == "acc":
- if printLog:
- print(f"[{index}]{spacer}{instruction[0]} with arg {instruction[1]}{instruction[2]}", end="")
- if instruction[1] == "+":
- acc += instruction[2]
- elif instruction[1] == "-":
- acc -= instruction[2]
- if printLog:
- print(f", global acc: {acc}")
- return index + 1, acc
- elif instruction[0] == "jmp":
- if printLog:
- print(f"[{index}]{spacer}{instruction[0]} {instruction[1]}{instruction[2]}", end="")
- if instruction[1] == "+":
- if printLog:
- print(f", jmping to {index + instruction[2]}")
- return index + instruction[2], acc
- elif instruction[1] == "-":
- if printLog:
- print(f", jmping to {index - instruction[2]}")
- return index - instruction[2], acc
- else:
- print(f"{instruction} not valid!")
- exit(1)
- def runProgram(_program, printLog = False):
- acc = 0
- index = 0
- executedInstructions = []
- while True:
- if index >= len(program):
- result = (acc, index, "Out of bounds")
- return result
- instruction = _program[index]
- #print(f"\n{executedInstructions}")
- if index not in executedInstructions:
- executedInstructions.append(index)
- executedInstructions.sort()
- result = execute(index, instruction, acc, printLog)
- index = result[0]
- acc = result[1]
- else:
- result = (acc, index, "Recursion")
- return result
- print(runProgram(program))
- print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement