Advertisement
Musical_Muze

Day 5, Part 1

Dec 6th, 2019
1,224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | None | 0 0
  1. #extract the code from the file and load it into an array for processing
  2. input1 = open("intcode.txt", "r")
  3. code = input1.read()
  4. input1.close()
  5. code = code.split(",")
  6.  
  7. #the array elements are currently strings; turn them into integers
  8. for i in range(len(code)):
  9.     code[i] = int(code[i])
  10.  
  11. #function to return a five-element array to represent the intcode
  12. def intcodeArray(int1):
  13.     intcode = list(str(int1))
  14.     if(len(intcode)<5):
  15.         for i in range(5-len(intcode)):
  16.             intcode.insert(0,"0")
  17.     for i in range(len(intcode)):
  18.         intcode[i] = int(intcode[i])
  19.     return intcode
  20.  
  21. ##inst[4] and inst[3] are the opcode
  22. ##inst[2] is the mode of the first parameter
  23. ##inst[1] is the mode of the second parameter
  24.  
  25. #function to return the value of a position, given its mode
  26. def value(mode, position):
  27.     val = 0
  28.     if(mode==0):
  29.         val = code[code[position]]
  30.     else:
  31.         val = code[position]
  32.     return val
  33.  
  34. pos = 0
  35.  
  36. #run the intcode
  37. while(code[pos]!=99):
  38.    
  39.     inst = intcodeArray(code[pos])
  40.  
  41.     #add two values
  42.     if(inst[4]==1):
  43.        
  44.         two = pos+1
  45.         three = pos+2
  46.         four = code[pos+3]
  47.        
  48.         code[four] = value(inst[2],two) + value(inst[1],three)
  49.         pos += 4
  50.  
  51.     #multiply two values
  52.     elif(inst[4]==2):
  53.        
  54.         two = pos+1
  55.         three = pos+2
  56.         four = code[pos+3]
  57.  
  58.         code[four] = value(inst[2],two) * value(inst[1],three)
  59.         pos += 4
  60.  
  61.     #take an input value
  62.     elif(inst[4]==3):
  63.         print("What is your input value?")
  64.         choice = input()
  65.         choice = int(choice)
  66.         if(inst[2]==0):
  67.             code[code[pos+1]] = choice
  68.         else:
  69.             code[pos+1] = choice
  70.         pos += 2
  71.  
  72.     #print an output value
  73.     elif(inst[4]==4):
  74.         print(value(inst[2],(pos+1)))
  75.         pos += 2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement