Advertisement
Armandur

Untitled

Dec 8th, 2020
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.15 KB | None | 0 0
  1. program = []
  2.  
  3. with open("8 - input", 'r') as file:
  4.     lines = file.readlines()
  5.     for line in lines:
  6.         line = line.strip("\n")
  7.         program.append([line.split(" ")[0], line.split(" ")[1][0], int(line.split(" ")[1][1:])])
  8.  
  9. def execute(index, instruction, acc, printLog=False):
  10.     spacer = "\t"
  11.     if index < 10:
  12.         spacer = spacer * 2
  13.     if instruction[0] == "nop":
  14.         if printLog:
  15.             print(f"[{index}]{spacer}{instruction[0]}")
  16.         return index + 1, acc
  17.     elif instruction[0] == "acc":
  18.         if printLog:
  19.             print(f"[{index}]{spacer}{instruction[0]} with arg {instruction[1]}{instruction[2]}", end="")
  20.         if instruction[1] == "+":
  21.             acc += instruction[2]
  22.         elif instruction[1] == "-":
  23.             acc -= instruction[2]
  24.         if printLog:
  25.             print(f", global acc: {acc}")
  26.         return index + 1, acc
  27.     elif instruction[0] == "jmp":
  28.         if printLog:
  29.             print(f"[{index}]{spacer}{instruction[0]} {instruction[1]}{instruction[2]}", end="")
  30.         if instruction[1] == "+":
  31.             if printLog:
  32.                 print(f", jmping to {index + instruction[2]}")
  33.             return index + instruction[2], acc
  34.         elif instruction[1] == "-":
  35.             if printLog:
  36.                 print(f", jmping to {index - instruction[2]}")
  37.             return index - instruction[2], acc
  38.     else:
  39.         print(f"{instruction} not valid!")
  40.         exit(1)
  41.  
  42. def runProgram(_program, printLog = False):
  43.     acc = 0
  44.     index = 0
  45.     executedInstructions = []
  46.     while True:
  47.         if index >= len(program):
  48.             result = (acc, index, "Out of bounds")
  49.             return result
  50.  
  51.         instruction = _program[index]
  52.         #print(f"\n{executedInstructions}")
  53.         if index not in executedInstructions:
  54.             executedInstructions.append(index)
  55.             executedInstructions.sort()
  56.             result = execute(index, instruction, acc, printLog)
  57.             index = result[0]
  58.             acc = result[1]
  59.         else:
  60.             result = (acc, index, "Recursion")
  61.             return result
  62.  
  63.  
  64. print(runProgram(program))
  65. print()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement