Пример #1
0
def part1():
    with open("../inputs/day17.txt") as f:
        pc = intcode.Computer()
        code = f.read().strip()
        pc.load_program(code)
    out, ascii = ascii_out()
    pc.set_io(out=ascii)
    pc.run()
    out = [row for row in out if len(row) != 0]
    #print('\n'.join(''.join(row) for row in out))
    alignment = 0
    for y, row in enumerate(out):
        for x, obj in enumerate(row):
            if obj == "#":
                i = 0
                if x > 0:
                    i += out[y][x - 1] == "#"
                if x < len(row) - 1:
                    i += out[y][x + 1] == "#"
                if y > 0:
                    i += out[y - 1][x] == "#"
                if y < len(out) - 1:
                    i += out[y + 1][x] == "#"
                if i == 4:
                    alignment += x * y
    print(f"Alignment: {alignment}")
    return out
Пример #2
0
def part2(out):
    with open("../inputs/day17.txt") as f:
        pc = intcode.Computer()
        code = f.read().strip()
        pc.load_program(code)
    path = create_path(out)
    routines = compress_path(path)
    compiled = compile_routines(routines)
    dust = 0

    def in_(_):
        x = compiled.pop(0)
        print(chr(x), end="")
        return x

    def out(o):
        nonlocal dust
        if o > 256:
            dust = o
        else:
            print(chr(o), end="")

    pc.memory[0] = 2
    pc.set_io(in_=in_, out=out)
    pc.run()
    print("Dust collected:", dust)
def part1(raw_input):
    print("Part 1")
    computer = intcode.Computer(raw_input)
    computer.generator = computer.run()
    print(chr(computer.generator.send(None)), end='', sep='')
    commands = deque([
        'west', 'take mug', 'north', 'take easter egg', 'south', 'east',
        'south', 'east', 'north', 'take candy cane', 'south', 'west', 'north',
        'east', 'take coin', 'north', 'north', 'take hypercube', 'south',
        'east', 'take manifold', 'west', 'south', 'south', 'east',
        'take pointer', 'west', 'west', 'take astrolabe', 'north', 'east',
        'north', 'drop manifold', 'drop easter egg', 'drop pointer',
        'drop candy cane', 'east'])
        
    while True:
        text = []
        try:
            while output := next(computer.generator):
                text.append(chr(output))
        except StopIteration:
            pass
        print(''.join(text))
        command = commands.popleft() if commands else input()
        if command == 'exit': return
        for c in command:
            output = computer.generator.send(ord(c))
            if output: print(chr(output), end='')
        computer.generator.send(ord('\n'))
Пример #4
0
def part1():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__),
                           "../inputs/day5.txt")) as f:
        print("Provide '1' as input")
        pc.load_program(f.read().strip())
        pc.run()
Пример #5
0
def solve_part_b(want_debug):
    a_prog, b_prog, c_prog, soln = find_solution(PART_B_PATH)

    input_data[0] = 2  # change to part B
    in_q = Queue()
    out_q = Queue()
    computer = intcode.Computer(input_data, in_q, out_q)

    write_str(in_q, soln)
    write_str(in_q, a_prog)
    write_str(in_q, b_prog)
    write_str(in_q, c_prog)

    write_str(in_q, 'y' if want_debug else 'n')

    if want_debug:
        computer.run_async()
        while not computer.stopped:
            grid = read_grid(out_q)
            os.system('clear')
            time.sleep(.001)
            print_grid(grid)
    else:
        computer.run()
        last_num = 0
        buf = []
        while not out_q.empty():
            buf.append(out_q.get())
        print(''.join([chr(x) for x in buf[:-1]]))
        print('dust collected : %d' % buf[-1])
Пример #6
0
 def __init__(self, last_cmd, inp=None):
     self.num_outputs = []
     istream = sys.stdin
     if inp is not None:
         istream = StringIO.StringIO(inp)
     self.q = EchoQueue(last_cmd, istream, sys.stdout, self.num_outputs)
     self.computer = intcode.Computer("day21.data", self.q, self.q)
Пример #7
0
def part2(raw_input):
    print("Part 2")
    maximum = float('-inf')
    phase_permutations = itertools.permutations(range(5, 10), 5)
    for phase_settings in phase_permutations:
        computers = []
        num_amplifiers = len(phase_settings)
        outputs = [0] * num_amplifiers
        for i in range(num_amplifiers):
            computers.append(intcode.Computer(raw_input))
            computers[i].generator = computers[i].run()
            computers[i].generator.send(None)
            computers[i].generator.send(phase_settings[i])
        flag = True
        while flag:
            for i in range(num_amplifiers):
                try:
                    outputs[i] = computers[i].generator.send(outputs[(i - 1) %
                                                                     5])
                    next(computers[i].generator)
                except StopIteration:
                    flag = False
                    continue
        maximum = max(maximum, outputs[-1])
    return maximum
Пример #8
0
def part1():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__), "../inputs/day11.txt")) as f:
        prog = f.read().strip()
    painting = True
    painted = {}
    x, y = 0, 0
    dir = 0
    def camera(_):
        return painted.get((x, y), 0)
    def paint_or_turn(o):
        nonlocal painting, x, y, dir
        assert o == 0 or o == 1
        if painting:
            painted[x, y] = o
        else:
            if o == 0:
                dir = (dir - 1) % 4
            else:
                dir = (dir + 1) % 4
            if dir == 0:
                y += 1
            elif dir == 1:
                x += 1
            elif dir == 2:
                y -= 1
            elif dir == 3:
                x -= 1
        painting = not painting
    pc.set_io(in_=camera, out=paint_or_turn)
    pc.load_program(prog)
    pc.run()
    print(len(painted.keys()))
Пример #9
0
def part2():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__),
                           "../inputs/day13.txt")) as f:
        prog = f.read().strip()
    pc.load_program(prog)
    ball_pos = 0
    paddle_pos = 0
    score = -1
    screen = {}

    def joystick(_):
        if ball_pos < paddle_pos:
            return -1
        elif ball_pos > paddle_pos:
            return 1
        else:
            return 0

    def draw_tile(x, y, id):
        nonlocal score, paddle_pos, ball_pos
        x, y, id = map(int, (x, y, id))
        if x == -1 and y == 0:
            score = int(id)
        if id == PADDLE:
            paddle_pos = int(x)
        elif id == BALL:
            ball_pos = int(x)
        screen[int(x), int(y)] = id

    pc.set_io(in_=joystick, out=intcode.out_every(3, draw_tile))
    pc.memory[0] = 2
    pc.run()
    print(score)
Пример #10
0
def calc_thruster_signal(software, phase_settings):
    last_output = 0
    for p in phase_settings:
        amp = intcode.Computer(software, inputs=[p, last_output])
        assert len(amp.outputs) == 1
        last_output = amp.outputs[0]
    return last_output
Пример #11
0
def part1():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__),
                           "../inputs/day9.txt")) as f:
        prog = f.read().strip()
    pc.load_program(prog)
    pc.set_io(in_=lambda _: 1)
    pc.run()
Пример #12
0
def sandbox():
    print("first program:")
    c = intcode.Computer([
        109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0,
        99
    ])
    for o in c.run([]):
        print(o, end=",")
    print("\n")
    print("second program:")
    c = intcode.Computer([1102, 34915192, 34915192, 7, 4, 7, 99, 0])
    for o in c.run([]):
        print(o)
        print(f"length of o: {len(str(o))} (should be 16)")
    print("third program:")
    c = intcode.Computer([104, 1125899906842624, 99])
    for o in c.run([]):
        print(f"this should be 1125899906842624: {o}")
Пример #13
0
def part1(raw_input):
    print("Part 1")
    computer = intcode.Computer(raw_input)
    computer.set_memory(1, 12)
    computer.set_memory(2, 2)
    computer.generator = computer.run()
    for _ in computer.generator:
        pass
    return computer.get_memory(0)
Пример #14
0
def part1():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__), "../inputs/day2.txt")) as f:
        pc.load_program(f.read().strip())
        pc.memory[1] = 12
        pc.memory[2] = 2
        print(pc.memory)
        pc.run()
        return pc.memory[0]
Пример #15
0
def test_02():
    pc = intcode.Computer([1, 0, 0, 0, 99])
    pc.run()
    assert pc.data.toList() == [2, 0, 0, 0, 99]
    pc.reset(vals=[2, 3, 0, 3, 99]), pc.run()
    assert pc.data.toList() == [2, 3, 0, 6, 99]
    pc.reset(vals=[2, 4, 4, 5, 99, 0]), pc.run()
    assert pc.data.toList() == [2, 4, 4, 5, 99, 9801]
    pc.reset(vals=[1, 1, 1, 4, 99, 5, 6, 0, 99]), pc.run()
    assert pc.data.toList() == [30, 1, 1, 4, 2, 5, 6, 0, 99]
Пример #16
0
def part1(raw_input):
    print("Part 1")
    computer = intcode.Computer(raw_input)
    computer.generator = computer.run()
    computer.generator.send(None)
    computer.generator.send(1)
    outputs = []
    for output in computer.generator:
        outputs.append(output)
    return outputs[-1]
Пример #17
0
def part2(raw_input):
    print("Part 2")
    for noun in range(0, 100):
        for verb in range(0, 100):
            computer = intcode.Computer(raw_input)
            computer.set_memory(1, noun)
            computer.set_memory(2, verb)
            computer.generator = computer.run()
            for _ in computer.generator:
                pass
            if computer.get_memory(0) == 19690720:
                return 100 * noun + verb
Пример #18
0
def part2():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__), "../inputs/day2.txt")) as f:
        program = f.read().strip()
    for i in range(0, 100):
        for j in range(0, 100):
            pc.load_program(program)
            pc.memory[1] = i
            pc.memory[2] = j
            pc.run()
            if pc.memory[0] == 19690720:
                return 100 * i + j
    return "Error!"
Пример #19
0
    def __init__(self, input_program):
        self.in_q = Queue()
        self.out_q = Queue()
        self.computer = intcode.Computer(input_program, self.in_q, self.out_q)
        self.computer_thread = threading.Thread(target=self.computer.run)
        self.computer_thread.daemon = True
        self.computer_thread.start()

        self.coords = (0, 0)
        self.grid = {}
        self._set_grid_value(self.coords, '.')

        self.oxygen_coords = None
Пример #20
0
def part1():
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__),
                           "../inputs/day13.txt")) as f:
        prog = f.read().strip()
    pc.load_program(prog)
    screen = {}

    def draw_tile(x, y, id):
        screen[int(x), int(y)] = id

    pc.set_io(out=intcode.out_every(3, draw_tile))
    pc.run()
    print(sum(1 for x in screen.values() if x == BLOCK))
Пример #21
0
def part2():
    bgcolor("black")
    pensize(10)
    delay(0)
    speed(0)
    penup()
    seth(90)
    goto(-420, 75)
    dot(10)
    pc = intcode.Computer()
    with open(os.path.join(os.path.dirname(__file__), "../inputs/day11.txt")) as f:
        prog = f.read().strip()
    painting = True
    painted = {(0, 0): 1}
    x, y = 0, 0
    dir = 0
    def camera(_):
        nonlocal painted
        return painted.get((x, y), 0)
    def paint_or_turn(o):
        nonlocal painting, x, y, dir
        if painting:
            painted[x, y] = o
            if o == 0:
                color("black")
            else:
                color("white")
        else:
            if o == 0:
                dir = (dir - 1) % 4
                left(90)
            else:
                dir = (dir + 1) % 4
                right(90)
            if dir == 0:
                y += 1
            elif dir == 1:
                x += 1
            elif dir == 2:
                y -= 1
            elif dir == 3:
                x -= 1
            dot(20)
            forward(20)
        painting = not painting
    pc.set_io(in_=camera, out=paint_or_turn)
    pc.load_program(prog)
    pc.run()
    print(len(painted.keys()))
    done()
Пример #22
0
def part1(raw_input):
    print("Part 1")
    maximum = float('-inf')
    phase_permutations = itertools.permutations(range(5), 5)
    for phase_settings in phase_permutations:
        num_amplifiers = len(phase_settings)
        output = 0
        for i in range(num_amplifiers):
            computer = intcode.Computer(raw_input)
            computer.generator = computer.run()
            computer.generator.send(None)
            computer.generator.send(phase_settings[i])
            output = computer.generator.send(output)
        maximum = max(maximum, output)
    return maximum
Пример #23
0
def calc_thruster_signal_feedback(software, phase_settings):
    inputs = [[p] for p in phase_settings]
    inputs[0].append(0)
    computers = [
        intcode.Computer(software, inputs=i, run=False) for i in inputs
    ]
    last = computers[-1]
    while computers:
        c = computers.pop(0)
        done = c.run(partial=True)
        if len(computers) > 0:
            computers[0].inputs.append(c.outputs[-1])
        if not done:
            computers.append(c)
    return last.outputs[-1]
Пример #24
0
def check_coords(x, y):
    QueueFactory = intcode.SimpleQueue
    in_q = QueueFactory()
    in_q.put(x)
    in_q.put(y)
    out_q = QueueFactory()
    drone = intcode.Computer(_cached_tape, in_q, out_q)
    drone.run()
    out = out_q.get()
    if out == 1:
        return '#'
    elif out == 0:
        return '.'
    else:
        raise Exception('bad output: %s' % out)
Пример #25
0
def playground():
    q = CommandQueue()
    initial = []
    #initial = ['west', 'west', 'west']

    # Take all things and go to checkpoint.
    initial = [
        'MUTE', 'west', 'take cake', 'east', 'south', 'take coin', 'south',
        'west', 'north', 'north', 'north', 'inv', 'drop cake', 'north',
        'drop coin', 'north', 'take cake', 'take coin', 'north', 's', 'south',
        'south', 'east', 'inv', 'north', 'east', 'take mouse', 'south',
        'south', 'take hypercube', 'north', 'south', 'inv', 'north', 'north',
        'west', 'north', 'north', 'south', 'west', 'west', 'take pointer',
        'west', 'south', 'north', 'east', 'south', 'take monolith', 'north',
        'south', 'north', 'west', 'south', 'inv', 'take tambourine', 'east',
        'south', 'north', 'south', 'north', 'east', 'east', 'take mug', 'west',
        'west', 'west', 'north', 'east', 'east', 'east', 'south', 'south',
        'west', 'north', 'north', 'UNMUTE', 'north', 'inv'
    ]

    ITEMS = [
        'pointer', 'hypercube', 'cake', 'tambourine', 'monolith', 'mouse',
        'coin', 'mug'
    ]

    def _append_recursive_tries(items, initial):
        if not items:
            initial.append('inv')
            initial.append('north')
            return
        this_item = items.pop()
        initial.append('take %s' % this_item)
        _append_recursive_tries(items, initial)
        initial.append('drop %s' % this_item)
        _append_recursive_tries(items, initial)
        items.append(this_item)

    _append_recursive_tries(list(ITEMS), initial)

    for c in initial:
        q.commands.append(c)

    try:
        computer = intcode.Computer('day25.data', q, q)
        computer.run()
    except KeyboardInterrupt, EOFError:
        pass
Пример #26
0
def part1():
    robot = Robot(it.Computer(list(program), output_mode="return"))
    i = 0
    while robot.step():
        print(f"robot is walking... step {i}", end="\r")
        i += 1
    print(f"\n\nstep1 : robot painted {len(robot.grid.keys())} panels")
    print(
        f"will need an image of {robot.maxX - robot.minX} width x {robot.maxY - robot.minY} height"
    )
    imgFile = Image.new(
        "1", (robot.maxX - robot.minX + 40, robot.maxY - robot.minY + 60))
    for coords in robot.grid.keys():
        if robot.grid[coords] == 0:
            continue
        imgFile.putpixel((coords[0] - robot.minX + 2,
                          robot.maxY - coords[1] - robot.minY - 3), 1)
    imgFile.show()
Пример #27
0
def part1():
    computers = []
    network = Network()
    for i in range(2, 3):
        print(f"booting computer {i}")
        c = it.Computer(list(program))
        print(sum(c.program))
        print(c.rb)
        print(c.i)
        print(f"setting network address")
        r1 = c.run([i] + network.dequeue(i))
        if r1 != None:
            print(f"r1 was {r1}, get other output values")
            r2 = c.run([])
            r3 = c.run([])
            print([r1, r2, r3])
            network.enqueue(r1, r2, r3)
        print(c.rb)
        print(c.i)
        print(sum(c.program))
        computers.append(c)
Пример #28
0
def part2(raw_input):
    print("Part 2")
    computers = []
    input_queues = defaultdict(deque)
    network_size = 50
    nat = None, None
    last_nat_y = None

    for i in range(network_size):
        input_queues[i].append(i)
        computers.append(intcode.Computer(raw_input))
        computers[i].generator = computers[i].run()
        computers[i].generator.send(None)

    network_idle = False
    while True:
        if network_idle:
            x, y = nat
            if y == last_nat_y: return y
            input_queues[0].append(x)
            input_queues[0].append(y)
            last_nat_y = y

        network_idle = True
        for i in range(network_size):
            network_input = input_queues[i].popleft(
            ) if input_queues[i] else -1
            output = computers[i].generator.send(network_input)
            if network_input != -1: network_idle = False
            while output != None:
                address = output
                x = next(computers[i].generator)
                y = next(computers[i].generator)
                output = next(computers[i].generator)
                if address == 255:
                    nat = x, y
                else:
                    input_queues[address].append(x)
                    input_queues[address].append(y)
Пример #29
0
def part1(raw_input):
    print("Part 1")
    computers = []
    input_queues = defaultdict(deque)
    network_size = 50
    for i in range(network_size):
        input_queues[i].append(i)
        computers.append(intcode.Computer(raw_input))
        computers[i].generator = computers[i].run()
        computers[i].generator.send(None)

    while True:
        for i in range(network_size):
            network_input = input_queues[i].popleft(
            ) if input_queues[i] else -1
            output = computers[i].generator.send(network_input)
            if output:
                x = next(computers[i].generator)
                y = next(computers[i].generator)
                input_queues[output].append(x)
                input_queues[output].append(y)
                if output == 255: return y
Пример #30
0
def find_path_for_part_b():
    in_q = intcode.SimpleQueue()
    out_q = intcode.SimpleQueue()
    computer = intcode.Computer(input_data, in_q, out_q)
    computer.run()
    output = list(out_q.q)
    grid = read_grid(out_q)
    print_grid(grid)

    pos = (0, 10)  # From looking at the grid.
    direction = 1  # index into DIRECTIONS, from looking at grid.
    path = ['R']  # must be the first thing to do.
    segment_length = 0
    while True:
        front_pos = add_coords(pos, DIRECTIONS[direction])
        front_sq = look(grid, front_pos)
        if front_sq != '.':
            segment_length += 1
            pos = front_pos
            continue
        path.append(str(segment_length))
        segment_length = 0

        left_dir = (direction - 1) % 4
        left_pos = add_coords(pos, DIRECTIONS[left_dir])
        left_sq = look(grid, left_pos)
        right_dir = (direction + 1) % 4
        right_pos = add_coords(pos, DIRECTIONS[right_dir])
        right_sq = look(grid, right_pos)
        if left_sq != '.':
            assert right_sq == '.'
            direction = left_dir
            path.append('L')
        elif right_sq != '.':
            direction = right_dir
            path.append('R')
        else:  # Reached the end.
            print(','.join(path))
            return path