def main():
    computer = IntCodeComputer('day_17.input')
    computer.set_io_format(IntCodeComputer.UNICODE)
    memory, _, _ = computer.save()
    result = []
    # computer.run(output_data=result)
    # print("".join(result))
    # rows = "".join(result).split()
    # intersections = []
    # for y in range(len(rows) - 2):
    #     for x in range(len(rows[y]) - 2):
    #         if rows[y][x] == '#' and rows[y + 1][x] == '#' and rows[y - 1][x] == '#' and rows[y][x + 1] == '#' and rows[y][x - 1] == '#':
    #             intersections.append((x, y))
    # print(sum([x * y for x, y in intersections]))
    memory[0] = 2
    computer.load(memory, 0, 0)
    # 'R,10,R,8,L,10,L,10,R,8,L,6,L,6,R,8,L,6,L,6,R,10,R,8,L,10,L,10,L,10,R,10,L,6,R,8,L,6,L,6,L,10,R,10,L,6,L,10,R,10,L,6,R,8,L,6,L,6,R,10,R,8,L,10,L,10'
    input_data = [
        'B,A,A,B,C,A,C,C,A,B\n', 'R,8,L,6,L,6\n', 'R,10,R,8,L,10,L,10\n',
        'L,10,R,10,L,6\n', 'n\n'
    ]

    computer.run(input_data=[x for x in "".join(input_data)],
                 output_data=result)
    print(result)
 def test_day_2_part_1(self):
     computer = IntCodeComputer('day_2.input')
     program, counter, offset = computer.save()
     program[1] = 12
     program[2] = 2
     computer.load(program)
     computer.run()
     program, counter, offset = computer.save()
     self.assertEqual(3716293, program[0])
 def test_unicode(self):
     computer = IntCodeComputer()
     computer.load([
         1006, 17, 16, 4, 17, 1001, 4, 1, 4, 1001, 1, 1, 1, 1105, 1, 0, 99,
         72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33, 0
     ])
     computer.set_io_format(IntCodeComputer.UNICODE)
     result = []
     computer.run(output_data=result)
     self.assertEqual("Hello, World!", "".join(result))
def check_square(x, y):
    pc = IntCodeComputer(source='input', buffered=True)
    res_0 = pc.run([x, y])[0][0]
    pc = IntCodeComputer(source='input', buffered=True)
    res_1 = pc.run([x + 99, y])[0][0]
    pc = IntCodeComputer(source='input', buffered=True)
    res_2 = pc.run([x, y + 99])[0][0]
    pc = IntCodeComputer(source='input', buffered=True)
    res_3 = pc.run([x + 99, y + 99])[0][0]
    if res_0 and res_1 and res_2 and res_3:
        return 'SUCCESS! x,y = {},{}'.format(x, y)
 def test_day_5_part_1(self):
     computer = IntCodeComputer('day_5.input')
     result = []
     computer.run(input_data=[1], output_data=result)
     self.assertEqual(0, result[0])
     self.assertEqual(0, result[1])
     self.assertEqual(0, result[2])
     self.assertEqual(0, result[3])
     self.assertEqual(0, result[4])
     self.assertEqual(0, result[5])
     self.assertEqual(0, result[6])
     self.assertEqual(0, result[7])
     self.assertEqual(0, result[8])
     self.assertEqual(7157989, result[9])
Beispiel #6
0
class VacuumRobot:
    def __init__(self, instructions):
        self.map = np.zeros((100, 100), dtype=np.int8)
        self.start = (0, 0)  # row, col
        self.input_commands = []
        stdin = patient_generator(self.input_commands)
        self.computer = IntCodeComputer(stdin=stdin, stdout=None)
        self.computer_gen = self.computer.run(instructions)

    def load_camera_image(self):
        row_idx = 0
        col_idx = 0
        max_col = 0
        for pixel_val in self.computer_gen:
            if pixel_val == 10:
                # new line
                row_idx += 1
                col_idx = 0
                continue
            self.map[row_idx, col_idx] = pixel_val
            if col_idx > max_col:
                max_col = col_idx
            col_idx += 1
        self.map = self.map[:row_idx - 1, :max_col]

    def get_intersection_map(self):
        align_map = self.map == 35
        align_map[1:, :] &= self.map[:-1, :] == 35
        align_map[:-1, :] &= self.map[1:, :] == 35
        align_map[:, 1:] &= self.map[:, :-1] == 35
        align_map[:, :-1] &= self.map[:, 1:] == 35
        return align_map
    def test_day_11_part_1(self):
        computer = IntCodeComputer('day_11.input')
        drawn_tiles = []
        color_map = {}
        current_pos = (0, 0)
        current_direction = 0  # 0=up, 1=right, 2=down, 3=left
        exit_code = 1
        while exit_code != 0:
            input_data = [
                color_map[current_pos] if current_pos in color_map else 0
            ]
            result = []
            exit_code = computer.run(input_data=input_data, output_data=result)
            if len(result) > 0:
                color_map[current_pos] = result[0]
                drawn_tiles.append(current_pos)
                if result[1] == 0:
                    current_direction = (current_direction - 1) % 4
                elif result[1] == 1:
                    current_direction = (current_direction + 1) % 4

                if current_direction == 0:
                    current_pos = (current_pos[0], current_pos[1] + 1)
                elif current_direction == 1:
                    current_pos = (current_pos[0] + 1, current_pos[1])
                elif current_direction == 2:
                    current_pos = (current_pos[0], current_pos[1] - 1)
                elif current_direction == 3:
                    current_pos = (current_pos[0] - 1, current_pos[1])
        self.assertEqual(2343, len(set(drawn_tiles)))
 def test_day_2_part_2(self):
     value = None
     for i in range(0, 100):
         for j in range(0, 100):
             computer = IntCodeComputer('day_2.input')
             program, counter, offset = computer.save()
             program[1] = i
             program[2] = j
             computer.load(program)
             computer.run()
             program, counter, offset = computer.save()
             if program[0] == 19690720:
                 value = i * 100 + j
                 break
         if value:
             break
     self.assertEqual(6429, value)
Beispiel #9
0
def run_game(instructions):
    # tokens = 0  # part 1
    tokens = 2  # part 2
    human = False

    controller = [0]
    stdin = patient_generator(controller, default=sys.stdin if human else 0)
    computer = IntCodeComputer(stdin=stdin, stdout=None)
    if tokens:
        # insert token
        instructions[0] = tokens
    comp_gen = computer.run(instructions)
    rows = 22
    cols = 35
    game_canvas = np.zeros((rows, cols))
    canvas_row = "{}" * cols
    num_blocks = 0
    x_pos = next(comp_gen)
    y_pos = next(comp_gen)
    tile_id = next(comp_gen)
    paddle = (0, 0)
    sleep_time = 0.0
    score_str = ""

    while True:
        if x_pos == -1 and y_pos == 0:
            score_str = f"Score: {tile_id:d}"
        else:
            game_canvas[y_pos, x_pos] = tile_id
            num_blocks += int(tile_id == 2)
            if tile_id == 4:
                # ball
                if paddle[1] != x_pos and y_pos < paddle[0]:
                    controller.append(1 if paddle[1] < x_pos else -1)
            elif tile_id == 3:
                paddle = (y_pos, x_pos)
                sleep_time = 0.05

            if human:
                for row in game_canvas:
                    print(canvas_row.format(*(CANVAS_SYMBOLS[x] for x in row)))
                print(score_str)

        x_pos = next(comp_gen, None)
        y_pos = next(comp_gen, None)
        tile_id = next(comp_gen, None)
        if tile_id is None:
            break
        if human:
            sleep(sleep_time)
    if tokens:
        print(score_str)  # part 2
    else:
        print(num_blocks)  # part 1
Beispiel #10
0
def part1():
	print()
	print("Part 1")

	with open('input/07.txt') as f:
		program = list(map(int, f.read().strip().split(',')))
	computer = IntCodeComputer(program, debug=DebugFlag.OFF)
	
	mo = -1
	mv = None

	for phases in permutations(range(5)):

		last_input = 0
		for phase in phases:
			computer.run(input_vals=(phase, last_input))
			last_input = computer.output_value

		if last_input > mo:
			mo = last_input
			mv = phases

	print(mo, mv)
Beispiel #11
0
def paint(program, start_color):
    state = defaultdict(int)
    state[(0, 0)] = start_color
    c = IntCodeComputer(program=program)
    current_pos = (0, 0)
    heading = deque([(1, 0), (0, 1), (-1, 0), (0, -1)])

    while not c.HALTED:
        try:
            c.run()
        except InputInterrupt:
            c.inputs.append(state[current_pos])
        except OutputInterrupt:
            if len(c.outputs) < 2:
                continue
            paint, turn = c.outputs
            c.outputs = []
            state[current_pos] = paint
            if turn == 0:
                heading.rotate(-1)
            else:
                heading.rotate()
            current_pos = tuple(map(add, current_pos, heading[0]))
    return state
    def test_day_11_part_2(self):
        computer = IntCodeComputer('day_11.input')
        drawn_tiles = []
        color_map = {(0, 0): 1}
        current_pos = (0, 0)
        current_direction = 0  # 0=up, 1=right, 2=down, 3=left
        exit_code = 1
        while exit_code != 0:
            input_data = [
                color_map[current_pos] if current_pos in color_map else 0
            ]
            result = []
            exit_code = computer.run(input_data=input_data, output_data=result)
            if len(result) > 0:
                color_map[current_pos] = result[0]
                drawn_tiles.append(current_pos)
                if result[1] == 0:
                    current_direction = (current_direction - 1) % 4
                elif result[1] == 1:
                    current_direction = (current_direction + 1) % 4

                if current_direction == 0:
                    current_pos = (current_pos[0], current_pos[1] + 1)
                elif current_direction == 1:
                    current_pos = (current_pos[0] + 1, current_pos[1])
                elif current_direction == 2:
                    current_pos = (current_pos[0], current_pos[1] - 1)
                elif current_direction == 3:
                    current_pos = (current_pos[0] - 1, current_pos[1])

        max_x = max([x[0] for x in drawn_tiles])
        min_x = min([x[0] for x in drawn_tiles])
        max_y = max([x[1] for x in drawn_tiles])
        min_y = min([x[1] for x in drawn_tiles])
        drawn_result = []
        for y in range(max_y, min_y - 1, -1):
            drawn_result.append("".join([
                '█' if (x, y) in color_map and color_map[(x, y)] == 1 else ' '
                for x in range(min_x, max_x + 1)
            ]))
        self.assertListEqual([
            "   ██ ████ ███  ████ ███  ███  █  █ █  █   ",
            "    █ █    █  █ █    █  █ █  █ █  █ █  █   ",
            "    █ ███  ███  ███  █  █ ███  █  █ ████   ",
            "    █ █    █  █ █    ███  █  █ █  █ █  █   ",
            " █  █ █    █  █ █    █ █  █  █ █  █ █  █   ",
            "  ██  █    ███  ████ █  █ ███   ██  █  █   "
        ], drawn_result)
Beispiel #13
0
class Robot:
    def __init__(self,
                 initial_panel=0,
                 initial_pos=(50, 50),
                 grid_size=(100, 100)):
        # row, col
        self._pos = initial_pos
        # 0 = up
        # 1 = right
        # 2 = down
        # 3 = left
        self._dir = 0  # up
        self.grid_size = grid_size
        self.grid_state = np.zeros(grid_size, dtype=np.uint8)
        self.grid_painted = np.zeros(grid_size)
        self.grid_state[self._pos[0], self._pos[1]] = initial_panel
        self._stdin_colors = [self.grid_state[self._pos[0], self._pos[1]]]
        self._stdin = patient_generator(self._stdin_colors)
        self.computer = IntCodeComputer(stdin=self._stdin)
        self.panels_painted = 0

    def run(self, instructions):
        computer_gen = self.computer.run(instructions)
        for color_to_paint in computer_gen:
            # paint
            self.grid_state[self._pos[0], self._pos[1]] = color_to_paint
            if self.grid_painted[self._pos[0], self._pos[1]] == 0:
                self.grid_painted[self._pos[0], self._pos[1]] = 1
                self.panels_painted += 1

            # move
            turn_to_make = next(computer_gen)
            self._dir += 1 if turn_to_make == 1 else -1
            self._dir = self._dir % 4
            if self._dir in [0, 2]:
                # row is 0 at top
                mov = 1 if self._dir == 2 else -1
                # row, col
                self._pos = (self._pos[0] + mov, self._pos[1])
            elif self._dir in [1, 3]:
                mov = -1 if self._dir == 3 else 1
                self._pos = (self._pos[0], self._pos[1] + mov)
            else:
                raise RuntimeError("WTF Direction is {}!".format(self._dir))
            self._stdin_colors.append(self.grid_state[self._pos[0],
                                                      self._pos[1]])
Beispiel #14
0
def main():
    computer = IntCodeComputer('day_13.input')
    memory, counter, offset = computer.save()
    memory[0] = 2
    computer.load(memory)
    in_data = []
    out = 1
    result = []
    ball = None
    player = None
    while out:
        out = computer.run(input_data=in_data, output_data=result)
        game_plan = [result[x:x + 3] for x in range(0, len(result), 3)]
        color_map = {}
        for pixel in game_plan:
            if pixel[0] == -1 and pixel[1] == 0 and out == 0:
                print(pixel[2])
            if pixel[2] == 3:
                player = (pixel[0], pixel[1])
            if pixel[2] == 4:
                ball = (pixel[0], pixel[1])
            color_map[(pixel[0], pixel[1])] = pixel[2]
        # print([x[1] for x in color_map.items()].count(2))
        max_x = max([x[0] for x in game_plan])
        min_x = min([x[0] for x in game_plan])
        max_y = max([x[1] for x in game_plan])
        min_y = min([x[1] for x in game_plan])

        for y in range(min_y, max_y):
            print("".join([
                get_tile((x, y), color_map) for x in range(min_x, max_x + 1)
            ]))
        if out == 1 and ball and player:
            if ball[0] < player[0]:
                in_data = [-1]
            elif ball[0] > player[0]:
                in_data = [1]
            else:
                in_data = [0]
def main():
    """Main function that loads a program to the 'computer'."""
    computer = IntCodeComputer('day_11.input')
    drawn_tiles = []
    color_map = {(0, 0): 1}
    current_pos = (0, 0)
    current_direction = 0  # 0=up, 1=right, 2=down, 3=left
    exit_code = 1
    while exit_code != 0:
        input_data = [color_map[current_pos] if current_pos in color_map else 0]
        result = []
        exit_code = computer.run(input_data=input_data, output_data=result)
        if len(result) > 0:
            color_map[current_pos] = result[0]
            drawn_tiles.append(current_pos)
            if result[1] == 0:
                current_direction = (current_direction - 1) % 4
            elif result[1] == 1:
                current_direction = (current_direction + 1) % 4

            if current_direction == 0:
                current_pos = (current_pos[0], current_pos[1] + 1)
            elif current_direction == 1:
                current_pos = (current_pos[0] + 1, current_pos[1])
            elif current_direction == 2:
                current_pos = (current_pos[0], current_pos[1] - 1)
            elif current_direction == 3:
                current_pos = (current_pos[0] - 1, current_pos[1])

    print(len(set(drawn_tiles)))
    max_x = max([x[0] for x in drawn_tiles])
    min_x = min([x[0] for x in drawn_tiles])
    max_y = max([x[1] for x in drawn_tiles])
    min_y = min([x[1] for x in drawn_tiles])
    for y in range(max_y, min_y - 1, -1):
        print(
            "".join(['█' if (x, y) in color_map and color_map[(x, y)] == 1 else ' ' for x in range(min_x, max_x + 1)])
        )
Beispiel #16
0
from intcode import IntCodeComputer

code = [int(x) for x in open("input.txt", "r").readline().split(",")]
code[0] = 2

vacuum = IntCodeComputer(code)

mainprog = "A,A,B,C,C,A,B,C,A,B\n"
funcA = "L,12,L,12,R,12\n"
funcB = "L,8,L,8,R,12,L,8,L,8\n"
funcC = "L,10,R,8,R,12\n"

routines = [ord(x) for x in mainprog + funcA + funcB + funcC + "n\n"]

output = vacuum.run(routines)

print(output)
springscript = """\
NOT A J
NOT J J
AND B J
AND C J
NOT J J
AND D J
WALK
"""

inp = list(map(ord, springscript))

program = list(map(int, open('data/input21').read().strip().split(',')))
computer = IntCodeComputer(program, resume=False)
_, prints, status = computer.run(input_values=inp)

message = "".join([chr(p) for p in prints if p < 128])
print(message)
print(f"solution for part1: {prints[-1]}")

# part2

springscript = """\
NOT C J
AND H J
NOT B T
OR T J
NOT A T
OR T J
AND D J
Beispiel #18
0
            v1 = program[pos + 1]
            v2 = program[pos + 2]
            v1 = v1 if ops[-3] == 1 else program[v1]
            v2 = v2 if ops[-4] == 1 else program[v2]
            do_move = (v1 != 0 and opcode == 5) or (v1 == 0 and opcode == 6)
            if do_move:
                # print(f"Jumping to {pos}")
                pos = v2
            else:
                pos += 3
        elif opcode in [7, 8]:
            op = op_dict[opcode]
            v1 = program[pos + 1]
            v2 = program[pos + 2]
            v1 = v1 if ops[-3] == 1 else program[v1]
            v2 = v2 if ops[-4] == 1 else program[v2]
            resv = program[pos + 3]
            # print(f"{op.__name__} to {v1} and {v2} into {resv}")
            program[resv] = 1 if op(v1, v2) else 0
        pos += instr_steps[opcode]

    pos += 1
    if len(program) > pos:
        if program[pos] == 4:
            print(program[pos + 1])

    print("_________")

    computer = IntCodeComputer(inputs, inputs=[5])
    computer.run()
Beispiel #19
0
    0, 1106, 0, 587, 22102, 1, 1, -4, 21101, 0, 1, -1, 2207, -4, -2, 10, 1006,
    10, 648, 21102, 0, 1, -1, 22202, -2, -1, -2, 2107, 0, -3, 10, 1006, 10,
    670, 21202, -1, 1, 1, 21101, 670, 0, 0, 105, 1, 545, 21202, -2, -1, -2,
    22201, -4, -2, -4, 109, -5, 2106, 0, 0
]

brain = IntCodeComputer(code)

painted = set()
hull = defaultdict(int)

direction = 0  # 0 up, 1 right, 2 down, 3 left
x = 0
y = 0
while not brain.halted:
    result = brain.run([hull[(x, y)]])
    color = result[-2]
    turn = result[-1]

    hull[(x, y)] = color
    painted.add((x, y))

    if turn == 0:
        direction = (direction + 3) % 4
    elif turn == 1:
        direction = (direction + 1) % 4

    if direction == 0:  # up
        y -= 1
    elif direction == 1:  # right
        x += 1
Beispiel #20
0
def main():
    args, file_in = parse_args()
    instructions = np.loadtxt(file_in, delimiter=',', dtype=np.int)
    comp = IntCodeComputer(stdin=iter([1]))
    print(list(comp.run(instructions)))
        # Move forward 1:
        new_x = self.loc[0] + self.movements[self.direction][0]
        new_y = self.loc[1] + self.movements[self.direction][1]
        self.loc = (new_x, new_y)
        if self.loc not in self.hull:
            self.hull[self.loc] = 0

        return self.hull[self.loc]


if __name__ == '__main__':

    parser = argparse.ArgumentParser()
    parser.add_argument('--source', '-s', dest='source', default='input')
    args = parser.parse_args()

    h = Hull()
    pc = IntCodeComputer(args.source, buffered=True)

    inp = 0
    response = pc.run(inp)

    while response:

        inp = h.update(response)
        pc.run(inp)

        print(len(h.hull))

    input()
Beispiel #22
0
robot_pos = 0 + 0j
robot_orient = 1j
environment = {robot_pos: 1}
for nstep in range(10000):
    if DEBUG:
        print(f" ### starting: pos: {robot_pos}, orient: {robot_orient} ")
    if environment[robot_pos] == 2:
        if DEBUG: print(f"I've found something after {nstep} steps.")
        break
    else:
        if wall_left(environment, robot_pos, robot_orient, computer):
            if DEBUG: print(f"there's a wall left")
            if free_in_front(environment, robot_pos, robot_orient, computer):
                if DEBUG: print(f"it's free in front, I'm moving forward")
                step_forward = relative2absolute[robot_orient]
                program_state, prints, status = computer.run(
                    [step_forward.value])
                retval = prints[-1]
                assert retval != 0
                robot_pos = robot_pos + vectors[step_forward]
                environment[robot_pos] = retval
            else:
                if DEBUG: print(f"I have to rotate right")
                robot_orient = robot_orient * -1j
        else:
            if DEBUG: print(f"I will rotate left and move forward")
            # rotate left and move forward
            robot_orient = robot_orient * 1j
            step_forward = relative2absolute[robot_orient]
            program_state, prints, status = computer.run([step_forward.value])
            retval = prints[-1]
            assert retval != 0
 def test_day_9_part_2(self):
     computer = IntCodeComputer('day_9.input')
     output_data = []
     computer.run(input_data=[2], output_data=output_data)
     self.assertEqual(87571, output_data[0])
 def test_day_9_part_1(self):
     computer = IntCodeComputer('day_9.input')
     output_data = []
     computer.run(input_data=[1], output_data=output_data)
     self.assertEqual(2752191671, output_data[0])
Beispiel #25
0
from intcode import IntCodeComputer

pc = IntCodeComputer(source='input', buffered=True)
result = pc.run()
camera_out = result[0]


def render(screen):
    while screen:
        row = []
        while screen:
            ch = screen.pop(0)
            if ch == 10:
                break
            row.append(chr(ch))
        print(''.join(row))


render(camera_out)

move_routine = 'A,B,A,C,A,A,C,B,C,B\n'
A = 'L,12,L,8,R,12\n'
B = 'L,10,L,8,L,12,R,12\n'
C = 'R,12,L,8,L,10\n'
video_feed = 'n\n'

part2_inp = []
part2_inp += list(map(ord, list(move_routine)))
part2_inp += list(map(ord, list(A)))
part2_inp += list(map(ord, list(B)))
part2_inp += list(map(ord, list(C)))
Beispiel #26
0
from intcode import IntCodeComputer
c = IntCodeComputer()

if __name__ == "__main__":
    program = list(map(int, open('inputs/day5.txt').read().split(',')))

    diag = c.run(program.copy(), [1], [])
    print("Part 1:", c.outputs)

    diag = c.run(program.copy(), [5], [])
    print("Part 2:", c.outputs)
    if res_0 and res_1 and res_2 and res_3:
        return 'SUCCESS! x,y = {},{}'.format(x, y)


# with ProcessPoolExecutor(max_workers=100) as executor:
#     futures = executor.map(check_square, range(370, 10000), range(500, 10000))
#     for f in futures:
#         if f:
#             print(f)

# Part 2:
for y in range(650, 100000):
    print('checking row ', y)
    for x in range(37 * y // 50, 10000):
        pc = IntCodeComputer(source='input', buffered=True)
        result_1 = pc.run([x, y])[0][0]
        if result_1:
            pc = IntCodeComputer(source='input', buffered=True)
            result_2 = pc.run([x + 99, y])[0][0]
        else:
            result_2 = 0
        if result_1 and not result_2:
            break
        else:
            pc = IntCodeComputer(source='input', buffered=True)
            result_3 = pc.run([x, y + 99])[0][0]
            if result_2 and result_3:
                print('FOUND IT')
                print(x, y)
                break
 def test_day_5_part_2(self):
     computer = IntCodeComputer('day_5.input')
     result = []
     computer.run(input_data=[5], output_data=result)
     self.assertEqual(7873292, result[0])
def main():
    """Main function that loads a program to the 'computer'."""
    computer = IntCodeComputer('day_9.input')
    computer.run()
Beispiel #30
0
        self.last_ball_x = 0

    def act(self, paddle, ball):
        if paddle < ball:
            action = 1
        elif paddle == ball:
            action = 0
        elif paddle > ball:
            action = -1
        return action


if __name__ == '__main__':

    screen = {}
    pc = IntCodeComputer(source='input2', buffered=True)
    last_starfighter = AI()

    # Start game:
    result = pc.run(0)
    screen.update(get_blocks(result))

    while True:
        paddle, ball = draw_frame(screen)
        # inp = joystick()
        act = last_starfighter.act(paddle, ball)
        print(act)
        inp = act
        result = pc.run(int(inp))
        screen.update(get_blocks(result))