def runFeedbackLoop(cmdinput, ampinputs, startValue): #create the amplifiers. ampList = [] ampList.append(Intcode.Intcode(cmdinput, name="Amplifier A")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier B")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier C")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier D")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier E")) #start the amplifiers with the ampinputs. The first input of the Intcode #is the ampinput. for i, j in enumerate(ampList): j.setInputs([ampinputs[i]]) j.run() i = 0 end = 0 #This is the feedback loop. getFeedback will apply each amplifiers outputs #to the next amplifier, A->B->C->D->E->A. When getFeedback returns '99' #(opcode for the program finishing), then the feedback loop is done. #return the startValue which at the end will be the output of Amplifier E. while end != 99: ampList, end = getFeedback(cmdinput, ampList, startValue) startValue = ampList[-1].outputs[-1] #failsafe for infitite loop i += 1 if i > 100: break return startValue
def part2(cmdinput): boost = Intcode.Intcode(cmdinput, debug=True) boost.setInputs(2) boost.run()
def test2(): state = {} state['output'] = list() code = [109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99] codeCopy = code.copy() output = Intcode.Intcode(codeCopy, outputFunc=lambda x : addToList(state, 'output', x) ).Run() print( state ) assert( state['output'] == code and output[0] == code[0] ) state['expected'] = 34915192 * 34915192 output = Intcode.Intcode([1102,34915192,34915192,7,4,7,99,0], outputFunc=lambda x : storeOutput( state, 'output', x ) ).Run() assert( state['expected'] == state['output'] ) code = [104,1125899906842624,99] output = Intcode.Intcode(code, outputFunc=lambda x : storeOutput( state, 'output', x ) ).Run() assert( state['output'] == code[1] )
def Intcode_mp( progfunc, instanceId, inputQueue, outputQueue, haltQueue ): prog = progfunc() program = Intcode( prog, lambda : readInputQueue( instanceId, inputQueue ), lambda x: writeOutputQueue( instanceId, outputQueue, x ) ) try: program.Run() writeOutputQueue( instanceId+5, haltQueue, prog[0] ) except: print( program ) writeOutputQueue( instanceId+5, haltQueue, -1 )
def Intcode_mp(codefunc, instanceId, pipe): code = codefunc() try: ioHandler = MultiProcessIO(pipe, instanceId) prog = Intcode.Intcode(code, inputFunc=ioHandler.readInput, outputFunc=ioHandler.writeOutput) prog.Run() except: print('Failed to run Intcode for instance: {}'.format(instanceId)) raise
def __init__(self, prog): self.state = {} self.pos = (0, 0) self.dir = 'U' self.panels = {} self.outputs = [self.paintLoc, self.turn] self.outputcount = 0 self.io = [] self.prog = prog self.comp = Intcode.Intcode(self.prog, inputFunc=self.readCurrentPanel, outputFunc=self.handleOutput)
def runAmplifier(cmdinput, ampinputs, startValue): #this function creates the amplifiers, and runs a once pass through to get #the output of amplifier E. ampList = [] ampList.append(Intcode.Intcode(cmdinput, name="Amplifier A")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier B")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier C")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier D")) ampList.append(Intcode.Intcode(cmdinput, name="Amplifier E")) ampList[0].setInputs([ampinputs[0], startValue]) ampList[0].run() ampList[1].setInputs([ampinputs[1], ampList[0].outputs[-1]]) ampList[1].run() ampList[2].setInputs([ampinputs[2], ampList[1].outputs[-1]]) ampList[2].run() ampList[3].setInputs([ampinputs[3], ampList[2].outputs[-1]]) ampList[3].run() ampList[4].setInputs([ampinputs[4], ampList[3].outputs[-1]]) end = ampList[4].run() return ampList[4].outputs[-1]
def __init__(self, program): self.x = 0 self.y = 0 self.surface = Tiles.Hallway() self.output = [] self.Computer = Intcode.Intcode() self.Computer.memory = program self.Computer.increase_memory(10) self.Computer.output = asyncio.Queue() self.Computer.output_method = self.Computer.output.put_nowait self.output = asyncio.Queue() self.Computer.input_method = self.output.get self.untested_moves = [] self.direction = 1
def __init__(self): self.cur_pos = np.array([0,0]) #Current position of the droid (2D coordinate) self.game = Intcode(input_code) #north (1), south (2), west (3), and east (4) self.in_to_dirs = {1:tuple([1,0]), 2:tuple([-1,0]), 3:tuple([0,-1]), 4:tuple([0,1])} self.dirs_to_in = {tuple(v): int(k) for k, v in self.in_to_dirs.items()} #Reverse dictionary self.unexplored = [] #Buffer list for unexplored tiles adjacent to original position self.anti_clockwise = {1:3, 3:2, 2:4, 4:1} self.clockwise = {1:4, 4:2, 2:3, 3:1} self.reverse_dir = {1:2, 2:1, 3:4, 4:3} #0 = wall, 1=empty, 2=oxygen self.panels = {tuple(self.cur_pos): 0} #Panels of which we know the identity self.grid_num = 0 #counter for plots
def runtestcases(): if testcase == 1: continue elif testcase == 2: continue elif testcase == 3: continue test = Intcode.Intcode(cmdinput, debug=True) test.run() if testcase == 1: continue if testcase == 2: continue if testcase == 3: continue
def __init__(self, start_c): self.dir = np.array( (1, 0)) #Left: (0,-1), Down: (-1,0), Right: (0,1), Up: (1,0) self.panels = {} self.panels[(0, 0)] = start_c #Start on panel that is black or white self.cur_pos = np.array((0, 0)) self.brain = Intcode(input_code) self.anti_clockwise = { (-1, 0): (0, -1), (0, -1): (1, 0), (1, 0): (0, 1), (0, 1): (-1, 0) } self.clockwise = { (-1, 0): (0, 1), (0, 1): (1, 0), (1, 0): (0, -1), (0, -1): (-1, 0) }
def runtestcases(): if testcase == 1: cmdinput = [ 109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99 ] elif testcase == 2: cmdinput = [1102, 34915192, 34915192, 7, 4, 7, 99, 0] elif testcase == 3: cmdinput = [104, 1125899906842624, 99] test = Intcode.Intcode(cmdinput, debug=True) test.run() if testcase == 1: print(test.outputs) if cmdinput == test.outputs: print('PASSES!') else: print('FAILS!') if testcase == 2: print(test.outputs[-1]) if len(str(test.outputs[-1])) == 16: print('PASSES!') else: print('FAILS!') if testcase == 3: print(test.outputs[-1]) if test.outputs[-1] == 1125899906842624: print('PASSES!') else: print('FAILS!')
intersections += [(x, y)] return intersections def DrawIntersections(self, intersections): intersected = self.image.copy() for intersection in intersections: print(intersection) line = intersected[intersection[1]] newline = line[:intersection[0]] + 'O' + line[intersection[0] + 1:] intersected[intersection[1]] = newline print(newline) print('\n'.join(intersected)) def GetAlignmentParams(intersections): sum = 0 for intersection in intersections: sum += (intersection[0] * intersection[1]) return sum if __name__ == '__main__': scaffoldingImage = ScaffoldingImage() asciiProg = Intcode.Intcode(Intcode.readProgInput('input.txt'), outputFunc=scaffoldingImage.collectImage) asciiProg.Run() scaffoldingImage.Render() intersections = scaffoldingImage.FindIntersections() print(GetAlignmentParams(intersections)) #scaffoldingImage.DrawIntersections( intersections ) print(intersections)
numWalls = 0 numBlocks = 0 numHorizontalPaddle = 0 numBall = 0 numEmpty = 0 for y in self.screen: for x in self.screen[y]: val = self.screen[y][x] if 0 == val: numEmpty += 1 elif 1 == val: numWalls += 1 elif 2 == val: numBlocks += 1 elif 3 == val: numHorizontalPaddle += 1 elif 4 == val: numBall += 1 print(numEmpty, numWalls, numBlocks, numHorizontalPaddle, numBall) if __name__ == '__main__': myscreen = Screen() code = Intcode.readProgInput('input.txt') code[0] = 2 game = Intcode.Intcode(code, inputFunc=myscreen.getInput, outputFunc=myscreen.input) game.Run() myscreen.render() myscreen.countObjects()
def BOOST(): code = Intcode.readProgInput('input.txt') boostProg = Intcode.Intcode( code, lambda : 2 ) boostProg.Run()
def paint(self, color): self.surface.set_color(self.position, color) def camera(self): return self.surface.get_color(self.position) def output_handle(self, val): if not self.output_toggle: self.paint(val) self.output_toggle = not self.output_toggle return self.rotate(val) self.move() self.output_toggle = not self.output_toggle if __name__ == '__main__': with open('input', 'r') as f: program = f.read().split(',') PROG = [int(x) for x in program] COMP = Intcode.Intcode() COMP.memory = PROG COMP.increase_memory(10) ROB = Robot() ROB.surface.set_color((0, 0), 1) COMP.input_method = ROB.camera COMP.output_method = ROB.output_handle COMP.run() print(ROB.surface) print(len(ROB.surface.panels))
line = '' for x in range(50): if self.tractorMap[(x,y)] == 1: line += '#' count += 1 else: line += '.' lines += [ line ] print( '\n'.join(lines) ) return count class Coord: def __init__(self, x, y): self.output = [x, y] self.count = 0 def provideInput(self): self.count += 1 return self.output[self.count - 1] if __name__ == '__main__': scanner = TractorBeamScanner() prog = Intcode.readProgInput('input.txt') for y in range(50): for x in range(50): coord = Coord(x,y) tractorBeam = Intcode.Intcode( prog.copy(), inputFunc=coord.provideInput, outputFunc=lambda val : scanner.handleOutput(x, y, val) ) tractorBeam.Run() print( scanner.RenderAndCount() )
import Intcode memory_factor = 100 # Test 1 TEST_CODE = "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99".split( ",") TEST_CODE = [int(x) for x in TEST_CODE] computer = Intcode.Intcode() computer.memory = TEST_CODE.copy() computer.increase_memory(memory_factor) computer.run() print('Test 1', computer.output == TEST_CODE) #Test 2 TEST_CODE = "1102,34915192,34915192,7,4,7,99,0".split(",") TEST_CODE = [int(x) for x in TEST_CODE] computer = Intcode.Intcode() computer.memory = TEST_CODE.copy() computer.increase_memory(memory_factor) computer.run() print('Test 2', len(str(computer.output[0])) == 16) #Test 3 TEST_CODE = "104,1125899906842624,99".split(",") TEST_CODE = [int(x) for x in TEST_CODE] computer = Intcode.Intcode() computer.memory = TEST_CODE.copy() computer.increase_memory(memory_factor) computer.run() print('Test 3', computer.output[0] == TEST_CODE[1])
i = 0 while i < len(fileinput): if fileinput[i][0:4] == 'TEST': testinput = list(map(int,fileinput[i+1].split(','))) testoutput = list(map(int,fileinput[i+2].split(','))) testCases.append(IntcodeTest(fileinput[i],testinput,testoutput)) i += 3 i += 1 testpass = 0 failedID = [] for j in testCases: tempIntcode = Intcode.Intcode(j.testcase,debug=True) tempIntcode.run() testpass = printTestOutcome(tempIntcode,j,failedID,testpass) printTotalTestsOutcome(failedID,testpass,3) #numtests = len(cmdinput)/2 #print(cmdinput[0]) #test1 = Intcode.Intcode(cmdinput[0],name='Test #1',debug=True) #test1.run() #testpass = printTestOutcome(test1,testpass,1)
self.inputGather[2]) self.inputGather = [] def countObjects(self): numWalls = 0 numBlocks = 0 numHorizontalPaddle = 0 numBall = 0 numEmpty = 0 for y in self.screen: for x in self.screen[y]: val = self.screen[y][x] if 0 == val: numEmpty += 1 elif 1 == val: numWalls += 1 elif 2 == val: numBlocks += 1 elif 3 == val: numHorizontalPaddle += 1 elif 4 == val: numBall += 1 print(numEmpty, numWalls, numBlocks, numHorizontalPaddle, numBall) if __name__ == '__main__': myscreen = Screen() game = Intcode.Intcode(Intcode.readProgInput('input.txt'), outputFunc=myscreen.input) game.Run() myscreen.countObjects()
import Intcode if __name__ =="__main__": #read the numbers in readfile = open('aoc_day5_1.txt') fileinput = [] #read each line of the text file for line in readfile: fileinput.append(line) cmdinput = list(map(int,fileinput[0].split(','))) Intcode.Intcode(cmdinput,[5]).run() #comment
import asyncio import Intcode import Tiles if __name__ == '__main__': with open('input', 'r') as f: PROG = [int(x) for x in f.read().strip().split(',')] comp = Intcode.Intcode() comp.input_queue = asyncio.Queue() comp.input_method = comp.input_queue.get comp.output_queue = asyncio.Queue() comp.output_method = comp.output_queue.put_nowait def query_comp(pos): comp.memory = PROG.copy() comp.increase_memory(10) comp.cursor = 0 comp.relative_base = 0 comp.input_queue.put_nowait(pos[0]) comp.input_queue.put_nowait(pos[1]) loop = asyncio.get_event_loop() loop.run_until_complete(comp.run()) return comp.output_queue.get_nowait() def find_top_border(pos): c = query_comp(pos) while c != 1: pos = (pos[0], pos[1] + 1) c = query_comp(pos)
return self.output class SpringdroidInput: def __init__(self, inputProg): self.state = {} self.prog = inputProg self.step = '' self.pos = 0 def readInput(self): val = self.prog[self.pos] self.step += val self.pos += 1 if val == '\n': print(self.step) self.step = '' return ord(val) if __name__ == '__main__': collector = OutputCollector() springdroid = SpringdroidInput( 'NOT A T\nNOT B J\nOR T J\nNOT C T\nOR T J\nAND D J\nWALK\n') prog = Intcode.readProgInput('input.txt') droid = Intcode.Intcode(prog, outputFunc=collector.Output, inputFunc=springdroid.readInput) droid.Run() print(collector.Data())
self.inputCommand = list(map(ord, ['e','a','s','t'])) charval = self.done elif self.west == charval: self.inputCommand = list(map(ord, ['w','e','s','t'])) charval = self.done while charval != self.done: doEcho = True if charval == self.backspace: if len(self.inputCommand) > 0: self.inputCommand.pop(-1) else: doEcho = False else: self.inputCommand += [ord(charval)] if doEcho: print(charval, end='', flush=True) charval = click.getchar() self.lastInput = str(map(chr, self.inputCommand)) self.inputCommand += [ 10 ] return self.inputCommand.pop(0) if __name__ == '__main__': io = RobotIO() #input = Input() #mapOutput = MapOutput( input ) #input.SetOutput( mapOutput ) prog = Intcode.Intcode( Intcode.readProgInput('input.txt'), inputFunc=io.handleInput, outputFunc=io.handleOutput ) #mapOutput.Render() prog.Run()
round = 0 posMap[self.oxygenPos] = 'O' neighbors = [(1, 0), (-1, 0), (0, 1), (0, -1)] while len(addedOxygen) > 0: lastOxygen = addedOxygen.copy() addedOxygen = [] round += 1 for oxygen in lastOxygen: for neighbor in neighbors: possiblePos = MapOutput.AddPos(oxygen, neighbor) if posMap[possiblePos] == '.': posMap[possiblePos] = 'O' addedOxygen += [possiblePos] print("Took {} rounds to fill the space with Oxygen".format(round - 1)) def ValidateAndCalculateOxygenFill(self): if not self.Validate(): return False self.CalculateOxygenFill() return True if __name__ == '__main__': input = Input() mapOutput = MapOutput(input) input.SetOutput(mapOutput) prog = Intcode.Intcode(Intcode.readProgInput('input.txt'), inputFunc=input.readInput, outputFunc=mapOutput.HandleOutput) mapOutput.Render() prog.Run()
import numpy as np from Intcode import * from itertools import permutations with open("./Day9/input.txt") as file: input_code = [int(s) for s in file.read().strip().split(',')] IntComputer1 = Intcode(input_code) answer_part1 = IntComputer1.RunIntcode([1])[0] IntComputer2 = Intcode(input_code) answer_part2 = IntComputer2.RunIntcode([2])[0] print('Answer part 1: {}'.format(answer_part1)) print('Answer part 2: {}'.format(answer_part2))
def test_intcode_computer(lst): computer = Intcode() #print("###> dans test du int code et la list est : ", lst) lstRes = computer.computeIntcode(lst) #print("###> et la liste est mainteannt : ", lst) return lstRes
def test(): assert( [99] == Intcode.Intcode([99]).Run() )
import numpy as np import Intcode as ic # Modify computer data for noun in range(100): for verb in range(100): opcodes = np.genfromtxt("2019day2.csv", delimiter=",", dtype=int) print(noun, verb) opcodes[1] = noun opcodes[2] = verb x = ic.Intcode(opcodes) if (x.data[0] == 19690720): print(noun, verb, 100 * noun + verb) quit()
def BOOST(): code = readProgInput() boostProg = Intcode.Intcode(code, lambda: 1) boostProg.Run()