コード例 #1
0
def part2(input):
    comp = IntcodeComputer()
    comp.parse_input_string(input)
    mem = comp.mem
    x, y = 5, 2  # From part 1: y=1 is an empty row. (5,2) is the first point after (0,0)
    square_size = 100 - 1

    while (True):
        # Progress tracking
        if (y % 50 == 0):
            print('Trying y = {}, x = {} ...'.format(y, x))

        out = scan_point(comp, mem, x, y)
        if (out == 0):
            x += 1
        else:
            xs = x
            while (True):
                top_right = (xs + square_size, y)
                bottom_left = (xs, y + square_size)
                if (scan_point(comp, mem, *top_right) == 0):
                    y += 1
                    x = xs
                    break
                if (scan_point(comp, mem, *bottom_left) == 0):
                    xs += 1
                else:  # square fits into the beam
                    print(
                        'Square {} x {} fits into the beam. Top left corner: {}'
                        .format(square_size + 1, square_size + 1, (xs, y)))
                    return xs * 10000 + y
    return 0
コード例 #2
0
    def paint(self):
        opCode = None
        base=None
        nOut = 1
        currDir='UP'
        currPos=[self.start[0], self.start[1]]
        self.hull[currPos[0]][currPos[1]]=self.startColor
        pointer = None
        processedInstr = None
        while opCode != 99:
            
            computer = IntcodeComputer(processedInstr if processedInstr else
                                    self.instructions, [self.hull[currPos[0]][currPos[1]]], pointer if pointer else 0,base if base else 0)
            if not nOut % 2:
                pointer, outputDirection, processedInstr, opCode,base = computer.run('loop')
                
                nextD,nextP=self.nextPos(currPos,currDir, outputDirection)
                nOut += 1
                currPos=nextP
                currDir=nextD
            
            else:
                pointer, outputColor, processedInstr, opCode,base = computer.run('loop')
                
                if outputColor==0:
                    self.hull[currPos[0]][currPos[1]]=0
                if outputColor==1:
                    self.hull[currPos[0]][currPos[1]]=1 
                nOut += 1

                self.painted.setdefault(str(currPos[0])+str(currPos[1]),1 )
                
        return self.painted, self.hull
コード例 #3
0
def part1(input):
    comp = IntcodeComputer()
    comp.parse_input_string(input)
    mem = comp.mem
    affected_count = 0
    for i in range(50):
        for j in range(50):
            affected_count += scan_point(comp, mem, i, j)
    return affected_count
コード例 #4
0
ファイル: day9_1.py プロジェクト: MarkTee/aoc2019
def main():
    # Test Programs
    # program_filename = '../IntcodePrograms/test6.in'
    # program_filename = '../IntcodePrograms/test7.in'
    # program_filename = '../IntcodePrograms/test8.in'

    program_filename = '../IntcodePrograms/9.in'

    with open(program_filename) as f:
        program = list(map(int, f.readline().split(',')))
    computer = IntcodeComputer(program)
    computer.run_program()
コード例 #5
0
def main():
    """Identical to Day 9 - Part 1, except a different input is passed in."""

    # Test Programs
    # program_filename = '../IntcodePrograms/test6.in'
    # program_filename = '../IntcodePrograms/test7.in'
    # program_filename = '../IntcodePrograms/test8.in'

    program_filename = '../IntcodePrograms/9.in'

    with open(program_filename) as f:
        program = list(map(int, f.readline().split(',')))
    computer = IntcodeComputer(program)
    computer.run_program()
コード例 #6
0
ファイル: day13.py プロジェクト: meithan/AoC19
  def initiliaze(self, program):

    temp = {}
    self.computer = IntcodeComputer(program)

    while True:
      x, y, tileid = self.step()
      if self.computer.halted or (x == -1 and y == 0):
        break
      temp[(x,y)] = tileid

    xs = [p[0] for p in temp.keys()]
    ys = [p[1] for p in temp.keys()]
    xmin = min(xs)
    xmax = max(xs)
    ymin = min(ys)
    ymax = max(ys)
    self.nx = xmax - xmin + 1
    self.ny = ymax - ymin + 1

    self.tiles = []
    for i in range(self.nx):
      self.tiles.append([0]*self.ny)

    for pos in temp:
      x, y = pos
      tileid = temp[pos]
      self.tiles[x][y] = tileid
      if tileid == 4:
        self.ball_x = x
        self.ball_y = y
      elif tileid == 3:
        self.paddle_x = x
        self.paddle_y = y
      elif tileid == 2:
        if self.blocks is None:
          self.blocks = 1
        else:
          self.blocks += 1

    self.score = 0
コード例 #7
0
def part1(input):
    comp = IntcodeComputer()
    comp.parse_input_string(input)
    comp.run_until_input()
    output = comp.outputs
    # Visualize surface
    #layout = ''.join(list(map(str,output))).replace('35','#').replace('46','.').replace('10','\n').replace('94',chr(94))
    #print(layout)
    nodes = []
    x = y = 0
    # Add nodes
    for c in output:
        if (c==46):
            x += 1
        elif (c==10):
            x = 0
            y += 1
        else: # 46 or robot direction, for example 94
            nodes.append((x,y))
            x += 1
    # Count intersections
    align_param = 0
    for n in nodes:
        x,y = n
        neigbor_count = 0
        for neigbor in [(x+1,y),(x-1,y),(x,y+1),(x,y-1)]:
            if neigbor in nodes:
                neigbor_count += 1
        if (neigbor_count) > 2:
            align_param += x*y
    return align_param
コード例 #8
0
def part1(input):
    comp = IntcodeComputer()
    comp.init_memory(input)
    comp.run_until_input()
    #outputs = [1,2,3,6,5,4] # Test case
    outputs = comp.outputs
    block_count = 0
    for i in np.linspace(0,
                         len(outputs) - 3, int(len(outputs) / 3)).astype(int):
        _, _, id = outputs[i:i + 3]
        if (id == 2):
            block_count += 1
    return block_count
コード例 #9
0
def part1(input):
    comp = IntcodeComputer()
    comp.parse_input_string(input)
    comp.run_until_input()
    script = '''
    NOT C J
    AND D J 
    NOT A T 
    OR T J
    WALK
    '''
    run_springscript(comp, script)
    print(''.join([chr(c) for c in comp.outputs[:-1]]))

    return comp.output
コード例 #10
0
from IntcodeComputer import IntcodeComputer


def createMem(str): return list(map(int, str.strip("\n").split(",")))


f = open("aoc19.txt", "r")
mem = createMem(f.readline())

sz = 3

inputs = []
r, c = 5, 0
while True:
    r, c = r+1, c+1
    machine = IntcodeComputer(mem, list((r, c)))
    while(not machine.halted):
        machine.run()
    outputs = machine.output[:]
    while(outputs != [1]):
        print('ayy', r, c)
        c += 1
        mac = IntcodeComputer(mem, list((r, c)))
        while(not mac.halted):
            mac.run()
        outputs = mac.output[:]

    machine = IntcodeComputer(mem, list((r-(sz-1), c)))
    while(not machine.halted):
        machine.run()
    if machine.output != [1]:
コード例 #11
0
ファイル: 7a.py プロジェクト: varunjm/advent_of_code
import sys
import itertools
from IntcodeComputer import IntcodeComputer
f = open(sys.argv[1], "r")

program = [int(element) for element in f.readline().split(",")]

max_thrust = -1
max_thrust_phases = None
for phases in itertools.permutations([0, 1, 2, 3, 4]):
    Amplifier = [IntcodeComputer(program[:]) for c in range(0, 5)]
    output_signal = 0
    for idx, phase in enumerate(phases):
        Amplifier[idx].set_signal(output_signal)
        Amplifier[idx].set_phase(phase)
        output_signal = Amplifier[idx].run()
    if max_thrust < output_signal:
        max_thrust = output_signal
        max_thrust_phases = phases

print(max_thrust_phases)
print(max_thrust)
コード例 #12
0
ファイル: day7_2.py プロジェクト: MarkTee/aoc2019
def test():
    # basic intcode operations tests
    computer = IntcodeComputer([1,0,0,0,99])
    assert computer.run_program() == [2,0,0,0,99]

    computer = IntcodeComputer([2,3,0,3,99])
    assert computer.run_program() == [2,3,0,6,99]

    computer = IntcodeComputer([2,4,4,5,99,0])
    assert computer.run_program() == [2,4,4,5,99,9801]

    computer = IntcodeComputer([1,1,1,4,99,5,6,0,99])
    assert computer.run_program() == [30,1,1,4,2,5,6,0,99]

    computer = IntcodeComputer([1002,4,3,4,33])
    assert computer.run_program() == [1002,4,3,4,99]

    # amplifier tests
    program_filename = '../IntcodePrograms/test1.in'
    phase_sequence = [4,3,2,1,0]
    assert run_amplifiers(program_filename, phase_sequence) == 43210

    program_filename = '../IntcodePrograms/test2.in'
    phase_sequence = [0,1,2,3,4]
    assert run_amplifiers(program_filename, phase_sequence) == 54321

    program_filename = '../IntcodePrograms/test3.in'
    phase_sequence = [1,0,4,3,2]
    assert run_amplifiers(program_filename, phase_sequence) == 65210

    # amplifier feedback loop tests
    program_filename = '../IntcodePrograms/test4.in'
    phase_sequence = [9,8,7,6,5]
    assert run_amplifiers(program_filename, phase_sequence, feedback_loop=True) == 139629729

    program_filename = '../IntcodePrograms/test5.in'
    phase_sequence = [9,7,8,5,6]
    assert run_amplifiers(program_filename, phase_sequence, feedback_loop=True) == 18216
コード例 #13
0
import sys
from IntcodeComputer import IntcodeComputer

f = open(sys.argv[1], "r")
computer = IntcodeComputer([int(element) for element in f.read().split(",")])
computer.set_phase(None)
computer.set_signal(1)
print(computer.run())
コード例 #14
0
ファイル: day11.py プロジェクト: meithan/AoC19
class Robot:
    def __init__(self, program):
        self.program0 = program
        self.reset()

    def reset(self):
        self.computer = IntcodeComputer(program)
        self.panels = defaultdict(lambda: 0)

    def run(self, part):
        self.its = 0
        self.x = self.y = 0
        self.direction = "up"
        if part == 2:
            self.panels[(0, 0)] = 1
        while True:
            over_color = self.panels[(self.x, self.y)]
            # print(self.its, self.x, self.y, over_color, self.direction)
            self.computer.inputs.put(over_color)
            self.computer.execute(pause_on_output=True, quiet=True)
            self.computer.execute(pause_on_output=True, quiet=True)
            to_paint = self.computer.outputs[-2]
            turn_to = self.computer.outputs[-1]
            # print("paint:", to_paint)
            self.panels[(self.x, self.y)] = to_paint
            self.turn(turn_to)
            self.advance()
            # print("turn to:", turn_to)
            self.its += 1
            if self.computer.halted:
                if part == 1:
                    print("Part 1:", len(self.panels))
                    break
                elif part == 2:
                    print("Part 2:")
                    xs = [
                        x[0] for x in self.panels.keys() if self.panels[x] == 1
                    ]
                    ys = [
                        x[1] for x in self.panels.keys() if self.panels[x] == 1
                    ]
                    xmin, xmax = min(xs), max(xs)
                    ymin, ymax = min(ys), max(ys)
                    for y in range(ymax, ymin - 1, -1):
                        for x in range(xmin, xmax + 1):
                            if (x, y) in self.panels and self.panels[(x,
                                                                      y)] == 1:
                                print("#", end="")
                            else:
                                print(" ", end="")
                            print(" ", end="")
                        print()
                    break

    def turn(self, turn_to):
        if turn_to == 0:
            if self.direction == "up": self.direction = "left"
            elif self.direction == "left": self.direction = "down"
            elif self.direction == "down": self.direction = "right"
            elif self.direction == "right": self.direction = "up"
        elif turn_to == 1:
            if self.direction == "up": self.direction = "right"
            elif self.direction == "right": self.direction = "down"
            elif self.direction == "down": self.direction = "left"
            elif self.direction == "left": self.direction = "up"

    def advance(self):
        if self.direction == "up": self.y += 1
        elif self.direction == "right": self.x += 1
        elif self.direction == "left": self.x -= 1
        elif self.direction == "down": self.y -= 1
コード例 #15
0
ファイル: day13.py プロジェクト: meithan/AoC19
class Game:

  def __init__(self):
    self.computer = None
    self.score = None
    self.ball_x = None
    self.ball_y = None
    self.paddle_x = None
    self.paddle_y = None
    self.blocks = None

  def initiliaze(self, program):

    temp = {}
    self.computer = IntcodeComputer(program)

    while True:
      x, y, tileid = self.step()
      if self.computer.halted or (x == -1 and y == 0):
        break
      temp[(x,y)] = tileid

    xs = [p[0] for p in temp.keys()]
    ys = [p[1] for p in temp.keys()]
    xmin = min(xs)
    xmax = max(xs)
    ymin = min(ys)
    ymax = max(ys)
    self.nx = xmax - xmin + 1
    self.ny = ymax - ymin + 1

    self.tiles = []
    for i in range(self.nx):
      self.tiles.append([0]*self.ny)

    for pos in temp:
      x, y = pos
      tileid = temp[pos]
      self.tiles[x][y] = tileid
      if tileid == 4:
        self.ball_x = x
        self.ball_y = y
      elif tileid == 3:
        self.paddle_x = x
        self.paddle_y = y
      elif tileid == 2:
        if self.blocks is None:
          self.blocks = 1
        else:
          self.blocks += 1

    self.score = 0

  def update(self, x, y, tileid):
    self.tiles[x][y] = tileid
    if tileid == 3:
      self.paddle_x = x
      self.paddle_y = y
    elif tileid == 4:
      self.ball_x = x
      self.ball_y = y
    elif x == -1:
      self.score = tileid

  def autoplay(self):

    self.computer.inputs.put(0)

    while True:
      x, y, tileid = self.step()
      if x is None:
        break
      self.update(x, y, tileid)
      if tileid == 3:
        os.system('clear')
        self.draw()
        # time.sleep(0.0001)
      elif tileid == 4:
        self.computer.inputs.queue.clear()
        if self.paddle_x < self.ball_x:
          self.computer.inputs.put(1)
        elif self.paddle_x > self.ball_x:
          self.computer.inputs.put(-1)
        else:
          self.computer.inputs.put(0)
    os.system('clear')
    self.draw()

  def step(self):
    self.computer.execute(quiet=True, pause_on_output=True)
    self.computer.execute(quiet=True, pause_on_output=True)
    self.computer.execute(quiet=True, pause_on_output=True)
    if len(self.computer.outputs) >= 3:
      x = self.computer.outputs[-3]
      y = self.computer.outputs[-2]
      tileid = self.computer.outputs[-1]
    else:
      return None, None, None
    self.computer.outputs = []
    return x, y, tileid

  def draw(self):
    for y in range(self.ny):
      symbols = []
      for x in range(self.nx):
        if self.tiles[x][y] == 0:
          symbols.append(" ")
        elif self.tiles[x][y] == 1:
          symbols.append("#")
        elif self.tiles[x][y] == 2:
          symbols.append("B")
        elif self.tiles[x][y] == 3:
          symbols.append("=")
        elif self.tiles[x][y] == 4:
          symbols.append("o")
      print("".join(symbols))
    print("Score:", self.score)
コード例 #16
0
ファイル: day09.py プロジェクト: meithan/AoC19
import sys

from IntcodeComputer import IntcodeComputer

# =================================================

with open(sys.argv[1]) as f:
  program = [int(x) for x in f.readline().split(",")]

# Part 1: run with input = 1
# Part 2: run with input = 2
computer = IntcodeComputer(program)
computer.execute()
コード例 #17
0
import os
from IntcodeComputer import IntcodeComputer


def createMem(str): return list(map(int, str.strip("\n").split(",")))


f = open("aoc14.txt", "r")

machine = IntcodeComputer(createMem(f.readline()))
while(not machine.halted):
    machine.run()
コード例 #18
0
ファイル: main.py プロジェクト: CodyDBrown/AOC
def partOneMain():
    numbers = fileToList("input.txt")
    # print(numbers)
    #numbers = [3,12,6,12,15,1,13,14,13,4,13,99,-1,0,1,9]
    IntcodeComputer(numbers)
コード例 #19
0
ファイル: day11.py プロジェクト: meithan/AoC19
 def reset(self):
     self.computer = IntcodeComputer(program)
     self.panels = defaultdict(lambda: 0)
コード例 #20
0

def make_mac_output(machine):
    retnow = machine.run()
    if retnow == 'input':
        return
    retnow = machine.run()
    if retnow == 'input':
        return
    machine.run()
    return


machines = []
for i in range(50):
    mac = IntcodeComputer(createMem(open("aoc23.txt", "r").readline()), [i])
    machines.append(mac)

for i in range(50):
    print(machines[i], machines[i].inputQ)


def part1():
    while True:
        for i in range(50):
            machine = machines[i]

            make_mac_output(machine)

            dest, x, y = None, None, None
            if len(machine.output) == 3:
コード例 #21
0
ファイル: 13b.py プロジェクト: varunjm/advent_of_code
def next_input():
  global game_map
  global ball
  global paddle
  # for y in range(0, 25):
  #   for x in range(0, 42):
  #     if (x, y) in game_map and game_map[(x, y)] != 0:
  #       print (game_map[(x, y)], end='')
  #     else:
  #       print (' ', end='')
  #   print ('')
  # print("_________________________________________________________________________________")
  code_input_val = -1 if paddle > ball else 1 if paddle < ball else 0
  return code_input_val

computer = IntcodeComputer([int(element) for element in f.read().split(",")], stop_at_print=True, DEBUG=False, input_func=next_input)
computer.set_mem(0, 2)
ball = -1
paddle = -1
while True:
  x = computer.run()
  if x == None:
    break
  y = computer.run()
  tile_id = computer.run()
  if x == -1 and y == 0:
    print ('Score', tile_id)
  ball = x if tile_id == 4 else ball
  paddle = x if tile_id == 3 else paddle
  game_map[(x,y)] = tile_id
コード例 #22
0
ファイル: 2a.py プロジェクト: varunjm/advent_of_code
import sys
from IntcodeComputer import IntcodeComputer

f = open(sys.argv[1], "r")
program = [int(element) for element in f.read().split(",")]
program[1] = 12  #noun
program[2] = 2  #verb
computer = IntcodeComputer(program)
computer.run()
print(computer.fetch_mem(0))
コード例 #23
0
'''
current vies of scaffolds

sum of the alignment parameters 
    of the scaffold intersections
'''
import os
from IntcodeComputer import IntcodeComputer, createMemFromStr
from collections import defaultdict

asciii = {35: '#', 46: ".", 10: "\n"}
f = open("aoc17.txt", "r")

machine = IntcodeComputer(createMemFromStr(f.readline()))
while (not machine.halted):
    machine.run()
for i in range(100):
    print(i % 10, end='')
print()
row = 0
for i in machine.output:
    if chr(i) == '\n':
        print(row, end='')
        row += 1
    print(chr(i), end='')
for i in range(100):
    print(i % 10, end='')
''' googled
24*8
+48*14
+46*18
コード例 #24
0
Then, the program will output two values:
    First, it will output a value indicating the color to paint the panel the robot is over:
        0 means to paint the panel black, and 1 means to paint the panel white.

    Second, it will output a value indicating the direction the robot should turn:
        0 means it should turn left 90 degrees, and 1 means it should turn right 90 degrees.
'''


def createMem(str):
    return list(map(int, str.strip("\n").split(",")))


f = open("aoc11.txt", "r")

robot = IntcodeComputer(createMem(f.readline()))
direct, pos, visited = 0, [0, 0], {}
increments = {0: (0, 1), 1: (1, 0), 2: (0, -1), 3: (-1, 0)}
while (not robot.halted):
    robot.run([visited.get(tuple(pos), 0)])
    robot.run()

    if robot.output:
        visited[tuple(pos)] = robot.output[0]
        direct += 1 if robot.output[1] == 1 else -1
        if direct == 4: direct = 0
        if direct == -1: direct = 3
        inc = increments[direct]
        pos = ([i + j for i, j in zip(pos, inc)])
        robot.output.clear()
# print(emergencyHullvisited)
コード例 #25
0
def part2(input):
    # Set first memory loc = 2 to start playing
    input[0] = 2

    # Set up the drawing window
    screen = pygame.display.set_mode([1000, 600])
    pygame.display.set_caption('Arcade block game')
    pygame.font.init()
    myfont = pygame.font.SysFont('Comic Sans MS', 30)

    # Initilize Intcode computer & run until 1st input
    comp = IntcodeComputer()
    comp.init_memory(input)
    comp_input = 0
    comp.run_until_input()
    # #outputs = [1,2,3,6,5,4] # Test case
    outputs_start = comp.outputs
    walls, blocks = [[] for _ in range(2)]
    for i in np.linspace(0,
                         len(outputs_start) - 3,
                         int(len(outputs_start) / 3)).astype(int):
        x, y, id = outputs_start[i:i + 3]
        if (id == 1):
            walls.append((x, y))
        elif (id == 2):
            blocks.append((x, y))
        elif (id == 3):
            paddle = [x, y]
        else:  # 4 - ball
            ball = (x, y)
    blocks = set(blocks)

    # Run game until the user presses close
    score = 0
    running = True
    while running:
        # Exit if user clicks close
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

        # Decide input based on paddle & ball position
        if paddle[0] < ball[0]:
            comp_input = 1
        elif paddle[0] > ball[0]:
            comp_input = -1
        else:
            comp_input = 0
        # Run Intcode computer until next input
        comp.input = comp_input
        comp.run_until_input()
        outputs = comp.outputs
        # Update score & position of empty tiles, ball & paddle after each input
        for i in np.linspace(0,
                             len(outputs) - 3,
                             int(len(outputs) / 3)).astype(int):
            x, y, id = outputs[i:i + 3]
            if (x == -1 and y == 0):
                score = id
            elif (id == 0):
                if ((x, y) in blocks):
                    blocks.remove((x, y))
            elif (id == 3):
                paddle = [x, y]
            elif (id == 4):
                ball = (x, y)
        comp.outputs = []
        # Fill the background with white
        screen.fill((255, 255, 255))
        # Draw walls
        for w in walls:
            draw_tile(screen, w, BLACK)
        # Draw blocks
        for b in blocks:
            draw_tile(screen, b, GREEN)
        # Draw paddle
        draw_tile(screen, paddle, BLUE)
        # Draw ball
        draw_ball(screen, ball, RED)
        # Print score on game screen
        textsurface = myfont.render('Score: {}'.format(score), False, ORANGE)
        screen.blit(textsurface, (400, 10))
        # Refresh display & draw frame
        pygame.display.flip()
        # Pauses before next frame
        time.sleep((1000 / FPS) / 1000)
    return score
コード例 #26
0
ファイル: 9a.py プロジェクト: varunjm/advent_of_code
import sys
from IntcodeComputer import IntcodeComputer

f = open(sys.argv[1], "r")
computer = IntcodeComputer([int(element) for element in f.read().split(",")],
                           stop_at_print=False,
                           DEBUG=False)
computer.set_phase(None)
computer.set_signal(1)
print(computer.run())
コード例 #27
0
def part1(input):
    node_dict = {}
    map_graph = nx.Graph()
    opposites = {'north':'south', 'south':'north', 'east':'west', 'west':'east'}
    comp = IntcodeComputer()
    comp.parse_input_string(input)
    mem = comp.mem
    comp.run_until_input()

    root, room_desc, doors, items = parse_output(comp.outputs)
    node_dict[root] = {'desc': room_desc, 'doors': {door: False for door in doors}, 'items': items}
    comp.outputs = []
    map_graph.add_node(root)
    next_doors = deque([(root, door) for door in node_dict[root]['doors']])
    droid_loc = root

    # First, let droid run through all possible doors to scan the ship's floormap
    # In this run droid picks up no item => cannot get pass Pressure-Sensitive Floor
    print('Scanning ship\'s floor plan...')
    scan_path = []
    while(len(next_doors) > 0):
        scan_path.append(droid_loc)
        room, door = next_doors.pop()
        droid_loc = move_to_node(comp, map_graph, droid_loc, room) # Move/ backtrack droid from current room to the next node in stack
        node_dict[droid_loc]['doors'][door] = True # mark door as visited
        comp.ascii_command(door) # Order droid to go through door
        next_room, room_desc, doors, items = parse_output(comp.outputs)
        # door that droid went through to enter the room needs to be added first (popped last) in the stack
        # for example: droid enters a room via west door. It should try all north, east, south doors before bactracking via west door
        doors.remove(opposites[door])
        doors = [opposites[door]] + doors
        if next_room not in node_dict:
            node_dict[next_room] = {'desc': room_desc, 'doors': {door: False for door in doors}, 'items': items}
        comp.outputs = []
        # Add next room to graph if not already in graph
        if next_room not in map_graph:
            map_graph.add_node(next_room)
            map_graph.add_edge(droid_loc, next_room, directions = {droid_loc:door, next_room: opposites[door]})

        # Add new doors in the new room to stack
        droid_loc = next_room
        for d in node_dict[droid_loc]['doors']:
            if (not node_dict[droid_loc]['doors'][d]) and (not (droid_loc,d) in next_doors): 
                next_doors.append((droid_loc,d))
    print('Scanning done.\n')
    # print(scan_path)
    # #Visualize graph
    # visualize_graph(map_graph)

    # Use new droids to traverse from root to each rooms containing items.
    # Try to collect each item to see how droid reacts
    print('Try picking up each item...')
    collectable_items = {}
    for room in node_dict:
        items = node_dict[room]['items']
        if len(items) == 0:
            continue
        comp = IntcodeComputer()
        comp.init_memory(mem)
        droid_loc = move_to_node(comp, map_graph, root, room)
        print('--------------------------------------------')
        print('Room: {}. Item(s): {}'.format(room, items))
        for item in items:
            if (item == 'infinite loop'): 
                print('Item = infinite loop. If collected, IntCode computer is stuck in endless loop. Terminated.')
                comp.finished = True
                continue
            if (item == 'giant electromagnet'):
                print('Item = giant electromagnet. If collected, any further actions fail with message "The giant electromagnet is stuck to you. You can\'t move!! Command?". Terminated.')
                comp.finished = True
                continue
            comp.ascii_command('take ' + item)
            print((''.join([chr(c) for c in comp.outputs])).replace('\n','').replace('Command?',''))
            print('Computer finished: {}'.format(comp.finished))
            if(not(comp.finished)): 
                collectable_items[item] = room # If droid is still 'alive' after taking item, item is collectable
            comp.outputs = []

    print('\nCollectable items: {}'.format(collectable_items))
    
    # From above report: there are 8 collectable items
    # Now move 1 droid from root, pick up all collectable items and go to Security Checkpoint
    print('\nStart new droid from HullBreach, collect all items and move to SecurityCheckpoint...')
    comp = IntcodeComputer()
    comp.init_memory(mem)
    droid = root
    for item in collectable_items:
        room = collectable_items[item]
        print('Moved from {} to {}, collected item "{}"'.format(droid, room, item))
        droid = move_to_node(comp, map_graph, droid, room)
        comp.ascii_command('take ' + item)
        comp.outputs = []
    
    # Move to SecurityCheckpoint and drop all items there
    print('\nDropped all items at SecurityCheckpoint. Trying combinations of items to find the correct weight...')
    items = list(collectable_items.keys())
    droid = move_to_node(comp, map_graph, droid, 'SecurityCheckpoint', clear_output = False)
    for item in collectable_items:
        comp.ascii_command('drop ' + item)
        comp.outputs = []
        
    # Try every possible combinations of items until weight matches. Starting from all 8 items -> 7  items -> 6 items -> ...
    mem_snapshot = comp.mem.copy()
    pointer_snapshot = comp.pointer
    stop = False
    for n in reversed(range(1,9)): # [8,7,6,...,1]
        item_combs = list(combinations(items, n))
        for pickup_items in item_combs:
            comp.mem = mem_snapshot.copy() # revert computer to snapshot so as not having to come back to SecurityCheckpoint, drop items, etc.
            comp.pointer = pointer_snapshot
            for item in pickup_items:
                comp.ascii_command('take ' + item)
                comp.outputs = []
            droid = move_to_node(comp, map_graph, droid, 'Pressure-SensitiveFloor', clear_output = False)
            msg = (''.join([chr(c) for c in comp.outputs]))
            comp.outputs = []
            heavier = msg.find('Droids on this ship are lighter than the detected value!')
            lighter = msg.find('Droids on this ship are heavier than the detected value!')
            if (heavier > 0):
                print('Too heavy to pass Pressure-SensitiveFloor. Carrying {} items: {}'.format(len(pickup_items), pickup_items))
                droid = 'SecurityCheckpoint'
            if (lighter > 0):
                print('Too light to pass Pressure-SensitiveFloor. Carrying {} items: {}'.format(len(pickup_items), pickup_items))
                droid = 'SecurityCheckpoint'
            if(heavier == - 1 and lighter == -1):
                print('Correct weight to pass Pressure-SensitiveFloor. Carrying {} items: {}'.format(len(pickup_items), pickup_items))
                print(msg) # Final message that contains password
                stop = True
                break
        if stop: break
    return msg.split('by typing ')[1].split('on the keypad')[0]
コード例 #28
0
from IntcodeComputer import IntcodeComputer
import copy
import sys

f = open("input.txt", "r")


def createMem(str):
    return list(map(int, str.strip("\n").split(",")))


machine = IntcodeComputer(createMem(f.readline()))

# PART 1
# curr = ""
# while not machine.halted:
# 	v = machine.run()
# 	# print(v)
# 	if v is not None:
# 		curr += chr(v)

# print(curr)
# rows = curr.split("\n")
# grid = list(filter(None,rows))

# intersections = []
# for r in range(len(grid)):
# 	for c in range(len(grid[0])):
# 		if grid[r][c] == '#' and 1 <= r < len(grid) - 1 and 1 <= c < len(grid[0]) - 1:
# 			if grid[r-1][c] == '#' and grid[r+1][c] == '#' and grid[r][c-1] == '#' and grid[r][c+1] == '#':
# 				intersections.append((r,c))
コード例 #29
0
ファイル: day15.py プロジェクト: meithan/AoC19
      cmd = 2; dx = 0; dy = -1
    elif move == "w":
      cmd = 3; dx = -1; dy = 0
    elif move == "e":
      cmd = 4; dx = +1; dy = 0
    return cmd, dx, dy

  def get_opp(self, move):
    if move == "n": return "s"
    elif move == "s": return "n"
    elif move == "w": return "e"
    elif move == "e": return "w"

  def get_valid_moves(self, map, x, y):
    moves = []
    for move in ["n", "s", "e", "w"]:
      _, dx, dy = self.get_cmd_dx_dy(move)
      if map[(x+dx,y+dy)] != 0:
        moves.append(move)
    return moves

# =================================================

with open(sys.argv[1]) as f:
  program = [int(x) for x in f.readline().split(",")]

crawler = Crawler(IntcodeComputer(program))
crawler.build_map()
input()
crawler.propagate_oxygen()
コード例 #30
0
import sys
from IntcodeComputer import IntcodeComputer
import copy

f = open(sys.argv[1], 'r')

Intcode = [int(element) for element in f.read().split(",")]
# computer = IntcodeComputer(Intcode[:], stop_at_print=True, DEBUG=True)

space_map = dict()
dust = 0
count = 0
for y in range(0, 50):
  for x in range(0, 50):
    comp = IntcodeComputer(Intcode[:], stop_at_print=True, DEBUG=False)
    comp.set_phase(x)
    comp.set_signal(y)
    code = comp.run()
    count += int(code)
    print code, 
  print ''

print (count)