コード例 #1
0
ファイル: day25.py プロジェクト: will-snavely/adventofcode
def part1(path):
    safe_items = {
        "hypercube",
        "coin",
        "klein bottle",
        "shell",
        "easter egg",
        "astrolabe",
        "tambourine",
        "dark matter"
    }
    unsafe_items = {
        "photons",
        "giant electromagnet",
        "molten lava",
        "escape pod",
        "infinite loop"
    }
    controller = IntCodeProcess.compile(path)
    collect(set(), controller, None, unsafe_items)
    travel = ["west", "west", "north", "west", "south"]
    for cmd in travel:
        controller.send(*encode(cmd))
        controller.simulate()
        controller.flush()
    try_item_combos(controller, safe_items)
コード例 #2
0
def paint(program, starting_color=None):
    proc = IntCodeProcess(program)
    robot_x = 0
    robot_y = 0
    robot_direction = 0
    painted_panels = collections.defaultdict(list)
    if starting_color:
        painted_panels[(0, 0)].append(starting_color)
    while proc.state != "done":
        pos = (robot_x, robot_y)
        color = 0
        if pos in painted_panels:
            color = painted_panels[pos][-1]

        proc_input = color
        proc.send(proc_input)
        proc.run()
        outputs = proc.flush()
        if len(outputs) == 2:
            new_color = outputs[0]
            turn = outputs[1]
            painted_panels[pos].append(new_color)
            if turn == 1:
                robot_direction = (robot_direction + 1) % 4
            else:
                robot_direction = (robot_direction - 1) % 4
            if robot_direction == 0:
                robot_y += 1
            elif robot_direction == 1:
                robot_x += 1
            elif robot_direction == 2:
                robot_y -= 1
            elif robot_direction == 3:
                robot_x -= 1
    return painted_panels
コード例 #3
0
def run_script(intcode_path, script_path):
    with open(script_path) as f:
        script = f.readlines()
    controller = IntCodeProcess.compile(intcode_path)
    controller.simulate()
    print(decode(controller.flush()))
    for line in script:
        line = line.strip()
        if line:
            controller.send(*encode(line + "\n"))
    controller.simulate()
    print(decode(controller.flush()))
コード例 #4
0
ファイル: day19.py プロジェクト: will-snavely/adventofcode
def part1(path):
    controller = IntCodeProcess.compile(path)
    counter = 0
    for y in range(50):
        line = ""
        for x in range(50):
            if scan(controller, x, y) == 1:
                counter += 1
                line += "#"
            else:
                line += "."
    return counter
コード例 #5
0
def part1(path):
    icp = IntCodeProcess.compile(path)
    icp.simulate()
    output = icp.flush()
    image = parse_image(output)
    calibration = 0
    for row in range(len(image)):
        for col in range(len(image[row])):
            if image[row][col] == "#":
                if all(image[i][j] == "#"
                       for _, (i, j) in adj(image, (row, col))):
                    calibration += row * col
    print(calibration)
コード例 #6
0
def process(path):
    print("Input:", path)
    with open(path) as f:
        for line in f:
            program = [int(c) for c in line.split(",")]
            proc = IntCodeProcess(program)
            proc.send(2)
            proc.run()
            for o in proc.output:
                print(o)
コード例 #7
0
def part2(path):
    nic = IntCodeProcess.compile(path, io=NetworkIO)
    nodes = []
    outputs = []
    for n in range(50):
        node = nic.fork()
        node.send(n)
        outputs.append(collections.deque())
        nodes.append(node)

    nat_value = None
    last_nat_y = None

    while True:
        for idx, node in enumerate(nodes):
            node.simulate(budget=10)
            outputs[idx].extend(node.flush())
            while len(outputs[idx]) >= 3:
                addr = outputs[idx].popleft()
                x = outputs[idx].popleft()
                y = outputs[idx].popleft()
                if addr == 255:
                    nat_value = (x, y)
                else:
                    nodes[addr].send(x)
                    nodes[addr].send(y)

            if idx == len(nodes) - 1:
                idle = True
                for inner_node in nodes:
                    if inner_node.io.failed_reads <= 1:
                        idle = False
                        break
                if idle and nat_value is not None:
                    print(nat_value[1])
                    nodes[0].send(nat_value[0])
                    nodes[0].send(nat_value[1])
                    if last_nat_y == nat_value[1]:
                        return last_nat_y
                    last_nat_y = nat_value[1]
                    nat_value = None
コード例 #8
0
def part1(path):
    nic = IntCodeProcess.compile(path, io=NetworkIO)
    nodes = []
    outputs = []
    for n in range(50):
        node = nic.fork()
        node.send(n)
        outputs.append(collections.deque())
        nodes.append(node)

    while True:
        for idx, node in enumerate(nodes):
            node.simulate(budget=10)
            outputs[idx].extend(node.flush())
            while len(outputs[idx]) >= 3:
                addr = outputs[idx].popleft()
                x = outputs[idx].popleft()
                y = outputs[idx].popleft()
                if addr == 255:
                    return x, y
                nodes[addr].send(x)
                nodes[addr].send(y)
コード例 #9
0
ファイル: day13.py プロジェクト: will-snavely/adventofcode
def process(path):
    print("Input:", path)

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

    game = Game()
    proc = IntCodeProcess(program)
    proc.memory[0] = 2
    while not proc.done():
        proc.run()
        output = proc.flush()
        update(game, output)
        # draw(game, 40, 20)
        if game.ball_position[1] == 19:
            proc.memory[392] = game.ball_position[0] - 1
            proc.send(1)
        else:
            proc.send(0)
    print(game.ball_position, game.paddle_position, game.score)
コード例 #10
0
def part2(path):
    icp = IntCodeProcess.compile(path)
    icp.memory[0] = 2
    icp.simulate()
    output = icp.flush()
    image = parse_image(output)

    path, commands = pathfind(image, find(image, "^"))

    symbols = []
    for index in range(0, len(commands), 2):
        symbols.append((commands[index], commands[index + 1]))

    alphabet = set(symbols)
    letter_to_int = {}
    int_to_letter_str = {}
    for idx, letter in enumerate(alphabet):
        letter_to_int[letter] = idx
        int_to_letter_str[idx] = "{},{}".format(letter[0], letter[1])

    letter_size = {}
    for i, s in int_to_letter_str.items():
        letter_size[i] = len(s)

    sentence = [letter_to_int[symbol] for symbol in symbols]
    results = list()
    generate_encodings({}, sentence, 0, 0, [], results)
    suitable_encodings = []
    for encoding, sequence in results:
        suitable = True
        for transform in encoding:
            program_length = sum([letter_size[x]
                                  for x in transform]) + len(transform) - 1
            if program_length > 20:
                suitable = False
                break
        if suitable:
            suitable_encodings.append((encoding, sequence))

    labels = {0: "A", 1: "B", 2: "C"}
    if suitable_encodings:
        encoding, sequence = suitable_encodings[0]
    else:
        print("No suitable encodings found.")
        return

    programs = {}
    programs["main"] = ",".join([labels[elem] for elem in sequence])
    for seq, eid in encoding.items():
        programs[labels[eid]] = ",".join([int_to_letter_str[i] for i in seq])

    for prog in ["main", "A", "B", "C"]:
        print("Sending {}:".format(prog), programs[prog])
        for c in programs[prog]:
            icp.send(ord(c))
        icp.send(ord("\n"))
        icp.simulate()

    icp.send(ord("n"))
    icp.send(ord("\n"))
    icp.simulate()
    print(icp.flush()[-1])
コード例 #11
0
def move(controller: IntCodeProcess, command):
    controller.send(command)
    controller.run()
    output = controller.flush()
    return output[0]
コード例 #12
0
def main():
    for path in test_inputs:
        proc = IntCodeProcess.compile(path)
        solve(proc)
コード例 #13
0
ファイル: day19.py プロジェクト: will-snavely/adventofcode
def part2(path):
    parent = IntCodeProcess.compile(path)
    seen = {}

    def lookup(a, b):
        if (a, b) not in seen:
            seen[(a, b)] = scan(parent, a, b)
        return seen[(a, b)]

    def scan_line(b, offset=0):
        a = offset
        state = 0
        beam_start = None
        beam_end = None

        while a > 0:
            s = lookup(a, b)
            if s == 1:
                a -= 1
            else:
                break

        while state != 2:
            s = lookup(a, b)
            if state == 0:
                if s == 1:
                    beam_start = a
                    state = 1
            elif state == 1:
                if s == 0:
                    beam_end = a
                    state = 2
            a += 1
        return beam_start, beam_end

    def square_fits(a, b):
        corners = [
            lookup(a, b),
            lookup(a + 99, b),
            lookup(a, b + 99),
            lookup(a + 99, b + 99)
        ]
        return all(c == 1 for c in corners)

    left = 0
    right = 1000
    while left < right:
        mid = (right + left) // 2
        start, end = scan_line(mid, (mid * 3) // 5)
        fits = any(square_fits(off, mid) for off in range(start, end))
        if mid == left:
            break
        elif fits:
            right = mid
        else:
            left = mid

    line = left
    for cur_line in range(line - 10, line + 10):
        start, end = scan_line(cur_line, (cur_line * 3) // 5)
        for off in range(start, end):
            if square_fits(off, cur_line):
                return off, cur_line, off * 10000 + cur_line