예제 #1
0
def run_program(base_ints, noun, verb):
    ints = base_ints.copy()
    ints[1] = noun
    ints[2] = verb
    ic = IntCode(ints)
    ic.run_through()
    return ic.memory[0]
예제 #2
0
 def test_relative_mode_output(self):
     ic = IntCode(
         "109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99")
     ic.run()
     output = reversed(ic.output)
     output_code = ",".join([str(i) for i in output])
     self.assertEqual(ic._code, output_code)
예제 #3
0
 def run(self, raw_code):
     raw_code = "2" + raw_code[1:]
     self._arcade = {}
     self._score = None
     self._outputs = []
     computer = IntCode(raw_code, self._handle_input, self._handle_output)
     computer.run()
예제 #4
0
class Painting:
    def __init__(self, input_vals, initial_color=0):
        self.computer = IntCode(input_vals)
        self.direction = 0
        self.x, self.y = 0, 0
        self.painted = {(self.x, self.y): initial_color}

    def paint(self):
        while not self.computer.halted:
            starting_color = self.painted[(self.x, self.y)] if (
                self.x, self.y) in self.painted else 0
            color = self.computer.run(starting_color)
            self.painted[(self.x, self.y)] = color
            self.change_direction(self.computer.run(color))
            self.rotate()

    def change_direction(self, rotate_direction):
        if rotate_direction == 0:
            self.direction = (self.direction - 1) % 4
        else:
            self.direction = (self.direction + 1) % 4

    def rotate(self):
        if self.direction == 0:
            self.y += 1
        elif self.direction == 1:
            self.x += 1
        elif self.direction == 2:
            self.y -= 1
        elif self.direction == 3:
            self.x -= 1
def main():
    program = open_program('input')

    computer = IntCode(program, default_memory=8000)

    # J = (~A or ~B or ~C) and D

    computer._inputs.extend(string_to_ascii('NOT A T\n'))
    computer._inputs.extend(string_to_ascii('NOT B J\n'))
    computer._inputs.extend(string_to_ascii('OR T J\n'))
    computer._inputs.extend(string_to_ascii('NOT C T\n'))
    computer._inputs.extend(string_to_ascii('OR T J\n'))
    computer._inputs.extend(string_to_ascii('AND D J\n'))
    # computer._inputs.extend(string_to_ascii('WALK\n'))

    # J = J and (D and (E | H))

    computer._inputs.extend(string_to_ascii('NOT E T\n'))
    computer._inputs.extend(string_to_ascii('NOT T T\n'))
    computer._inputs.extend(string_to_ascii('OR H T\n'))
    computer._inputs.extend(string_to_ascii('AND D T\n'))
    computer._inputs.extend(string_to_ascii('AND T J\n'))
    computer._inputs.extend(string_to_ascii('RUN\n'))

    computer.run()

    for char in computer._outputs:
        try:
            print(chr(char), end='')
        except ValueError:
            return char
예제 #6
0
파일: 09.py 프로젝트: PiErr0r/aoc
def part_1(data):

    boost = IntCode(data, [1])
    boost.calculate()

    print('END OF PART1')
    return
예제 #7
0
파일: day13.py 프로젝트: kohrongying/aoc
def solve2():
    comp = IntCode('../input/day13.txt')
    paddle = (None, None)
    ball = (None, None)
    score = 0
    joystick = 0
    while True:
        outputs = comp.get_output(joystick, 3)
        if len(outputs) != 3:
            break
        x, y, tile_id = outputs
        if x == -1 and y == 0:
            score = tile_id
        if tile_id == 3:
            paddle = (x, y)
        elif tile_id == 4:
            ball = (x, y)

        if ball[0] is not None and paddle[0] is not None:
            if ball[0] < paddle[0]:
                joystick = -1
            elif ball[0] > paddle[0]:
                joystick = 1
            else:
                joystick = 0
        else:
            joystick = 0

    print('score', score)
예제 #8
0
파일: 25.py 프로젝트: thran/the_code
class Robot:
    def __init__(self):
        memory = list(map(int, open('input.txt').readlines()[0].split(',')))

        self.bot = IntCode(memory.copy())
        outputs = self.bot.run(inputs=[], halt_on_missing_input=True)
        self.show(outputs)

    def show(self, outputs):
        print(''.join(map(chr, outputs)))

    def run(self, command):
        outputs = self.bot.run(inputs=map(ord, command + '\n'), halt_on_missing_input=True)
        self.show(outputs)

    def solve(self, items):
        for count in range(1, len(items)):
            for its in combinations(items, count):
                for it in its:
                    self.run(f'take {it}')
                self.run('west')
                outputs = self.bot.run(inputs=map(ord, 'west\n'), halt_on_missing_input=True)
                outputs = ''.join(map(chr, outputs))
                if 'Alert' not in outputs:
                    self.run('inv')
                    return
                for it in its:
                    self.run(f'drop {it}')
예제 #9
0
def run_phase(seq):
    input_ = 0
    for phase in seq:
        ic = IntCode(raw, [phase, input_])
        ic.execute()
        input_ = ic.outputs[0]
    return input_
예제 #10
0
def part_1(loc=DEFAULT_INPUT):
    with open(loc) as f:
        memory = list(map(int, f.readline().rstrip().split(',')))
    ic = IntCode(memory)
    outputs = ic.run_through()
    draw_memory = list(zip(*[iter(outputs)] * 3))
    return sum(1 for t in draw_memory if t[2] == 2)
예제 #11
0
class Robot:
    def __init__(self, program, hull):
        self.intcode = IntCode(program, self.input_fn, self.output_fn)
        self.hull = hull
        self.pos = Point(0, 0)
        self.dir = Direction(0, -1)
        self.actions = itertools.cycle([self.paint, self.move])

    def input_fn(self):
        return self.hull[self.pos.tuple()]

    def output_fn(self, val):
        next(self.actions)(val)

    def paint(self, val):
        self.hull[self.pos.tuple()] = val

    def move(self, val):
        if val == 0:
            self.dir = self.dir.left()
        else:
            self.dir = self.dir.right()
        self.pos = self.pos.move(self.dir)

    def run(self):
        self.intcode.run()
예제 #12
0
def paint(instruction):
    machine = IntCode(instruction)

    turtle.speed(0)
    turtle.ht()
    turtle.tracer(0)

    marker = turtle.Turtle()

    marker.penup()
    marker.left(90)

    dot_distance = 10

    painted = {}

    color = 1
    direction = 1

    while not machine.halted:
        color = machine.run(direction)
        direction = machine.run(color)

        marker.write('#' if color == 1 else '.')

        if direction == 1:
            marker.right(90)
        elif direction == 0:
            marker.left(90)

        marker.forward(dot_distance)

    turtle.mainloop()
예제 #13
0
파일: 13.py 프로젝트: PiErr0r/aoc
def part_2(data):
	data[0] = 2
	game = IntCode(data, [])
	game.calculate()
	

	i = 0
	cnt = 0
	GRID = [[' . ' for i in range(44)] for j in range(23)]
	while not game.is_halted() and cnt < 10:
		screen = game.get_output(-1)
		i = 0
		while i < len(screen):
			[x, y, tile] = screen[i:i + 3] 
			if x == -1 and y == 0:
				print(tile)
				i += 3
				continue
			GRID[y][x] = t[tile]
			i += 3
		disp(GRID)
		game.unpause([0, 0, 0])
		game.calculate()
		cnt += 1

	print('END OF PART2')
	return 
예제 #14
0
def part_2(loc=DEFAULT_INPUT):
    with open(loc) as f:
        memory = list(map(int, f.readline().rstrip().split(',')))
    memory[0] = 2
    ic = IntCode(memory)
    score = -1
    paddle_x = 0
    while True:
        x = ic.get_output()
        y = ic.get_output()
        tile = ic.get_output()
        if x[0] or y[0] or tile[0]:
            return score
        if x[1] == -1 and y[1] == 0:
            score = tile[1]
        elif tile[1] == 3:
            paddle_x = x[1]
        elif tile[1] == 4:
            ball_x = x[1]
            if ball_x > paddle_x:
                ic.add_inputs(1)
            elif ball_x < paddle_x:
                ic.add_inputs(-1)
            else:
                ic.add_inputs(0)
예제 #15
0
파일: 09.py 프로젝트: PiErr0r/aoc
def part_2(data):

    boost = IntCode(data, [2])
    boost.calculate()

    print('END OF PART2')
    return
예제 #16
0
def loop_run(program, current_color=BLACK):
    heading = N
    position = 0
    painted_panels = {position: current_color}

    intcode = IntCode(program)

    while current_color is not None:
        input_value = current_color
        current_color = intcode.run(input_value)
        direction_value = intcode.run(input_value)

        if direction_value is None:
            break

        painted_panels[position] = current_color

        if direction_value not in (0, 1):
            raise RuntimeError(
                "Invalid direction value: {}".format(direction_value))

        heading = RIGHT * heading if direction_value else LEFT * heading
        position = position + heading
        current_color = painted_panels.get(position, BLACK)

        # print(f"direction={direction_value} color={current_color}")

    return painted_panels
예제 #17
0
def test_day_9():
    code = parse('109,1,204,-1,1001,100,1,100,1008,100,16,101,1006,101,0,99')
    prg = IntCode(code)
    prg.run()

    for c in code:
        assert c == prg.output.get()
예제 #18
0
파일: day15.py 프로젝트: kohrongying/aoc
def build_map():
  initialise_queue()
  while len(queue) > 0:
    curr_move = queue.pop(0)
    comp = IntCode('../input/day15.txt')
    comp, curr_pos = walk_curr_move(comp, curr_move)
    for m in movement_commands:
      output = comp.get_output(m, 1)[0]
      if output == 0:
        new_pos = get_coor(m, curr_pos)
        walls.add(new_pos)
      else:
        if output == 2:
          found = get_coor(m, curr_pos)
        new_move = copy.deepcopy(curr_move)
        new_move.append(m)
        new_pos = get_coor(m, curr_pos)
        if new_pos not in seen:
          seen.append(new_pos)
          queue.append(new_move)
        comp.get_output(opp[m], 1)
  print('found', found)

  f = open('day15-out2.txt', 'w')
  f.write(f'{found[0]} {found[1]} O\n')
  for i in walls:
    f.write(f'{i[0]} {i[0]} #\n')
  for j in seen:
    f.write(f'{i[0]} {i[0]} .\n')
예제 #19
0
 def __init__(self):
     memory = list(map(int, open('input.txt').readlines()[0].split(',')))
     self.arcade = IntCode(memory)
     self.field = np.zeros((44, 21))
     self.score = None
     self.ball_x = None
     self.pad_x = None
예제 #20
0
def part1(data):
    computer = IntCode(data)

    hull = defaultdict(int)
    loc = 0 + 0j
    direction = 1j

    input_color = 0  # black
    hull[loc] = input_color
    counter = {}
    while not computer.finished:
        computer.input.append(input_color)
        computer.run()
        # the computer will run, and then add things to their output
        new_color = computer.output[-2]
        new_turn = computer.output[-1]
        hull[loc] = new_color
        counter[loc] = 1
        if new_turn == 0:
            # turn left, multiply by 1j
            direction *= 1j
        else:
            # turn right, multiply by -1j
            direction *= -1j
        loc += direction
        input_color = hull[loc]

    return len(counter)
예제 #21
0
def part2():
    for i in range(100):
        for j in range(100):
            ic = IntCode(raw)
            ic.ins[1], ic.ins[2] = i, j
            ic.execute()
            if ic.ins[0] == 19690720:
                return 100 * i + j
예제 #22
0
 def __init__(self, code, start=0):
     self.brain = IntCode(code)
     # size = self.estimate_size(code)
     size = 1000
     self.pos = np.array([size, size])
     self.canvas = np.ones((size * 2, size * 2)) * -1
     self.dir = 0
     self.brain.input.append(start)
예제 #23
0
def test_day_9_2():
    code = parse('1102,34915192,34915192,7,4,7,99,0')
    prg = IntCode(code)

    prg.run()

    out = prg.output.get()

    assert len(str(out)) == 16
예제 #24
0
def test_day5_full():
    with open('day5_input.txt', 'r') as f:
        code = [int(t) for t in f.read().split(',')]

    prg = IntCode(code)
    prg.input.put(5)
    prg.run()
    result = prg.output.get()
    assert result == 15586959
예제 #25
0
def test_day_9_3():
    code = parse('104,1125899906842624,99')
    prg = IntCode(code)

    prg.run()

    out = prg.output.get()

    assert out == 1125899906842624
예제 #26
0
def part_1(loc=DEFAULT_INPUT):
    with open(loc) as f:
        memory = list(map(int, f.readline().rstrip().split(',')))
    #jump if (not A) or (not C and D)
    instructions = ['OR A J', 'AND C J', 'NOT J J', 'AND D J', 'WALK']
    ic = IntCode(memory)
    for inst in instructions:
        ic.add_ascii_inputs(inst)
    return ic.run_through()[-1]
예제 #27
0
파일: day13.py 프로젝트: kohrongying/aoc
def solve():
    # Change memory address 0 to 1
    comp = IntCode('../input/day13.txt')
    outputs = comp.get_output(0, -1)
    num_tiles = 0
    for i in range(0, len(outputs) - 3, 3):
        x, y, tile_id = outputs[i:i + 3]
        if tile_id == 2:
            num_tiles += 1
    print(num_tiles)
예제 #28
0
def part_1(loc=DEFAULT_INPUT):
    with open(loc) as f:
        memory = list(map(int, f.readline().rstrip().split(',')))
    s = 0
    for x in range(50):
        for y in range(50):
            ic = IntCode(memory.copy(), x, y)
            if ic.get_output()[1] == 1:
                s += 1
    return s
예제 #29
0
def test_day_9_boost():
    with open('day9_input.txt', 'r') as f:
        code = [int(s.strip()) for s in f.read().split(',')]

    prg = IntCode(code)
    prg.input.put(1)
    prg.run()

    assert prg.output.get() == 3780860499
    assert prg.output.empty()
예제 #30
0
파일: day02.py 프로젝트: borjasotomayor/AoC
def task1(prog):
    """
    Task 1: Set inputs and run program.
    """
    prog[1] = 12
    prog[2] = 2
    vm = IntCode(prog)
    vm.run()

    return vm.memory[0]