예제 #1
0
def test_location(x: int, y: int) -> bool:
    input_buffer = [x, y]
    def input_func() -> int:
        return input_buffer.pop(0)
    
    output_buffer = []
    def output_func(value: int):
        output_buffer.append(value)
    
    run_program(memory, input_func, output_func)
    output_value, = output_buffer
    return {0: False, 1: True}[output_value]
예제 #2
0
파일: 5.py 프로젝트: JohnGinger/aoc
def part_one(input_text):
    result = run_program(input_text, [1])
    output = next(result)
    while True:
        if output != 0:
            return output
        output = next(result)
예제 #3
0
def solve(data):
    tiles = {}
    def joystick():
        while True:
            print_tiles(tiles)
            paddle = [p for p in tiles if tiles[p] == 3][0]
            ball = [p for p in tiles if tiles[p] == 4][0]
            dist = abs(paddle[1] - ball[1])
            if dist == 0:
                yield 0
            elif ball[1] < paddle[1]:
                yield -1
            else:
                yield 1
    program = list(map(int, data.split(",")))
    program[0] = 2
    outputs = run_program(program, joystick)
    score = 0
    while True:
        try:
            x = next(outputs)
            y = next(outputs)
            tile = next(outputs)
            if (y, x) == (0, -1):
                score = tile
                print("Score:", score)
                print_tiles(tiles)
            else:
                tiles[(y, x)] = tile
        except StopIteration:
            break
    print(len(tiles))
    block_tiles = [(y, x) for (y, x) in tiles if tiles[(y, x)] == 2]
    print(len(block_tiles))
예제 #4
0
def part_one(input_text):
    max_value = 0
    for phase_settings in permutations([0, 1, 2, 3, 4], 5):
        value_so_far = 0
        for phase_setting in phase_settings:
            value_so_far = next(
                run_program(input_text, [phase_setting, value_so_far]))
        max_value = max(max_value, value_so_far)
    return max_value
예제 #5
0
def part_two(prog):
    program = list(map(int, prog.split(",")))
    phases = list(range(5, 10))
    max_thrust = float("-inf")
    for phase_perm in permutations(phases):
        loopback_thrust = 0

        def amp_a_input():
            yield phase_perm[0]
            while True:
                yield loopback_thrust

        def amp_b_input():
            yield phase_perm[1]
            for thrust in amp_a:
                yield thrust

        def amp_c_input():
            yield phase_perm[2]
            for thrust in amp_b:
                yield thrust

        def amp_d_input():
            yield phase_perm[3]
            for thrust in amp_c:
                yield thrust

        def amp_e_input():
            yield phase_perm[4]
            for thrust in amp_d:
                yield thrust

        amp_a = run_program(program.copy(), amp_a_input)
        amp_b = run_program(program.copy(), amp_b_input)
        amp_c = run_program(program.copy(), amp_c_input)
        amp_d = run_program(program.copy(), amp_d_input)
        amp_e = run_program(program.copy(), amp_e_input)
        for thrust in amp_e:
            loopback_thrust = thrust
            max_thrust = max(max_thrust, thrust)
    return max_thrust
예제 #6
0
 def work(net_addr):
     global NAT_X, NAT_Y
     og = run_program(program.copy(), create_receiver(net_addr))
     while not DIE.is_set():
         try:
             dest_net_addr, x, y = next(og), next(og), next(og)
             if dest_net_addr == 255:
                 with NAT_LOCK:
                     NAT_X, NAT_Y = x, y
                 continue
             queues[dest_net_addr].put((x, y))
         except StopIteration:
             break
예제 #7
0
def main():
    program = map(int, open("day17.input", "r").read().split(","))
    scaffold = [chr(o) for o in run_program(program)]
    print("".join(scaffold))

    program = list(map(int, open("day17.input", "r").read().split(",")))
    program[0] = 2

    def by_hand_counting():
        for function in [
                "A,B,A,C,B,C,B,A,C,B",
                "L,6,R,8,R,12,L,6,L,8",
                "L,10,L,8,R,12",
                "L,8,L,10,L,6,L,6",
                "n",
        ]:
            for c in function:
                yield ord(c)
            yield ord("\n")

    for o in run_program(program, by_hand_counting):
        pass
    print(int(o))
예제 #8
0
def part_two(input_text):
    max_value = 0
    for phase_settings in permutations([5, 6, 7, 8, 9], 5):
        value_so_far = 0
        last_val = 0

        a_list = [phase_settings[0], 0]
        b_list = [phase_settings[1]]
        c_list = [phase_settings[2]]
        d_list = [phase_settings[3]]
        e_list = [phase_settings[4]]

        a = run_program(input_text, a_list)
        b = run_program(input_text, b_list)
        c = run_program(input_text, c_list)
        d = run_program(input_text, d_list)
        e = run_program(input_text, e_list)

        i = 0
        while i < 100:

            b_list.append(next(a))
            c_list.append(next(b))
            d_list.append(next(c))
            e_list.append(next(d))
            value_so_far = next(e)

            if type(value_so_far) == int:
                last_val = value_so_far
                a_list.append(value_so_far)
            else:
                break
            i += 1

        max_value = max(max_value, last_val)
    return max_value
예제 #9
0
def amp(instructions, phase_settings, amp_input=None, feedback_loop=False):
    if amp_input is None:
        amp_input = [0]
        stdin = chain([phase_settings[0]], patient_generator(amp_input))
    else:
        stdin = chain([phase_settings[0]], amp_input)

    stdout_gen = run_program(instructions.copy(), stdin=stdin, stdout=None)
    if len(phase_settings) == 1:
        yield from stdout_gen
    elif feedback_loop and len(phase_settings) == 5:
        for out_val in amp(instructions,
                           phase_settings[1:],
                           amp_input=stdout_gen):
            amp_input.append(out_val)
            yield out_val
    else:
        yield from amp(instructions, phase_settings[1:], amp_input=stdout_gen)
예제 #10
0
def solve(data):
    maze = {(0, 0): "."}
    visited = {(0, 0): 0}
    please_visit = set([(-1, 0), (1, 0), (0, 1), (0, -1)])
    status_codes = Queue()
    def movement_commands():
        y, x = 0, 0
        dist = 0
        last_sc = None
        while len(please_visit) > 0:
            if (y, x) in visited:
                if (y+1, x) not in visited:
                    y += 1
                    yield north
                elif (y-1, x) not in visited:
                    y -= 1
                    yield south
                elif (y, x+1) not in visited:
                    x += 1
                    yield east
                elif (y, x-1) not in visited:
                    x -= 1
                    yield west
                else:
                    for movement in [north, south, west, east]:
                        dy, dx = get_dy_dx(movement)
                        if (y+dy, x+dx) in visited and visited[(y+dy, x+dx)] == dist-1:
                            y += dy
                            x += dx
                            dist -= 1
                            yield movement
                            last_sc = status_codes.get()
                            break
                    continue
                dist += 1
                last_sc = status_codes.get()
            visited[(y, x)] = dist
            please_visit.remove((y, x))
            if last_sc == sc_wall:
                maze[(y, x)] = "#"
                for movement in [north, south, west, east]:
                    dy, dx = get_dy_dx(movement)
                    if (y+dy, x+dx) in visited and visited[(y+dy, x+dx)] == dist-1:
                        y += dy
                        x += dx
                        dist -= 1
                        break
            elif sc == sc_moved:
                maze[(y, x)] = "."
                for dy, dx in map(get_dy_dx, [north, south, west, east]):
                    if (y+dy, x+dx) not in visited:
                        please_visit.add((y+dy, x+dx))
            elif sc == sc_goal:
                maze[(y, x)] = "G"
                for dy, dx in map(get_dy_dx, [north, south, west, east]):
                    if (y+dy, x+dx) not in visited:
                        please_visit.add((y+dy, x+dx))
                print(f"goal at {(y, x)}")

    outputs = run_program(map(int, data.split(",")), movement_commands)
    for sc in outputs:
        status_codes.put(sc)
    maze[(0, 0)] = "S"
    print_maze(maze)
예제 #11
0
파일: second.py 프로젝트: qxzcode/aoc_2019
                    if res is not None:
                        return res
                else:
                    # verify that the three funcs are a valid solution
                    if all(isinstance(x, int) for x in new_seq):
                        return new_seq, funcs

            # no solution was found
            return None

        seq, funcs = find_solution(full_seq, [[]])
        final_str = ','.join('ABC'[x] for x in seq)
        final_str += '\n'
        final_str += '\n'.join(make_str(func) for func in funcs)
        final_str += '\nn\n'
        self._input_buffer = list(final_str)

    def print_grid(self):
        for y in range(self.height):
            for x in range(self.width):
                char = '#' if self.grid[(x, y)] else '.'
                print(char, end='')
            print()


# run the program
camera = Camera(debug=False)
memory = load_memory(sys.argv[1])
memory[0] = 2
run_program(memory, camera.input_func, camera.output_func)
예제 #12
0
INPUT_STR = """\
NOT B J
NOT C T
OR T J
AND D J
NOT A T
OR T J
OR E T
OR H T
AND T J
RUN
"""
input_buffer = [ord(char) for char in INPUT_STR]


def input_func() -> int:
    value = input_buffer.pop(0)
    if DEBUG:
        print(chr(value), end='', flush=True)
    return value


def output_func(value: int):
    if value >= 128:
        print(value)
    elif DEBUG:
        print(chr(value), end='', flush=True)


run_program(memory, input_func, output_func)
예제 #13
0
from intcode import load_program, run_program

program = load_program("./5.in")
# stdin is defined as [1] in the problem
run_program(program, [1])
예제 #14
0
파일: p9.py 프로젝트: ghjm/advent2019
#!/usr/bin/python3
from intcode import run_program

print("Part 1: ", end='')
run_program("inputs/input9.txt", infunc=lambda:1, outfunc=print)
print("Part 2: ", end='')
run_program("inputs/input9.txt", infunc=lambda:2, outfunc=print)

예제 #15
0
import sys  # argv
import numpy as np

from game import Game
from intcode import load_memory, run_program

game = Game()

memory = load_memory(sys.argv[1])
run_program(memory, game.input_func, game.output_func)

print(np.count_nonzero(game.grid == 2))
예제 #16
0
                yield ord(ch)
            yield ord("\n")
        yield ord("R")
        yield ord("U")
        yield ord("N")
        yield ord("\n")

    return f


if __name__ == "__main__":
    instructions = ["NOT", "AND", "OR"]
    xs = "ABCDEFGHIJT"
    ys = ["J", "T"]
    program = list(map(int, open("day21.input", "r").read().split(",")))
    for length in range(16):
        print("length", length)
        possible_instructions = list(
            map(" ".join, product(instructions, xs, ys))
            for i in range(length + 1))
        for jumpscript in product(*possible_instructions):
            for i, o in enumerate(
                    run_program(program.copy(), jumpscript_guess(jumpscript))):
                if o > 255:
                    print(jumpscript)
                    print(i)
                    print(o)
                    exit(0)
                if i > 40:
                    break
예제 #17
0
def part_one(prog):
    program = list(map(int, prog.split(",")))
    outputs = list(run_program(program))
    return outputs
예제 #18
0
#!/usr/bin/python3

from intcode import run_program

print("Part 1:")
run_program("inputs/input5.txt", infunc=lambda: 1)

print("Part 2:")
run_program("inputs/input5.txt", infunc=lambda: 5)
예제 #19
0
drop ornament
drop klein bottle
drop dark matter
drop candy cane
drop hologram
drop astrolabe
drop whirled peas
drop tambourine
take astrolabe
take tambourine
take hologram
take klein bottle
north
"""


def semi_auto_input():
    for command in commands.splitlines():
        print(command)
        yield from map(ord, command)
        yield ord("\n")
    while True:
        yield from map(ord, input())
        yield ord("\n")


if __name__ == "__main__":
    program = map(int, open("day25.input", "r").read().split(","))
    for o in run_program(program, semi_auto_input):
        sys.stdout.write(chr(o))
예제 #20
0
파일: first.py 프로젝트: qxzcode/aoc_2019
            res = d if move_dir is None else move_dir
            if (x2, y2) in visited:
                continue
            if (x2, y2) not in grid:
                return res
            elif grid[(x2, y2)] != '#':
                queue.append((x2, y2))
            visited[(x2, y2)] = res
    raise RuntimeError('Everything explored')


robot = Robot(explore)

memory = load_memory(sys.argv[1])
try:
    run_program(memory, robot.input_func, robot.output_func)
except RuntimeError:
    pass


# perform a breadth-first search to count how far away the O2 system is
def get_dist_to_O2(grid):
    queue = [(0, 0)]
    visited = {(0, 0): 0}
    while queue:
        x, y = queue.pop(0)
        distance = visited[(x, y)] + 1
        for x2, y2, d in [(x + 1, y, 4), (x - 1, y, 3), (x, y + 1, 2),
                          (x, y - 1, 1)]:
            if (x2, y2) in visited:
                continue
예제 #21
0
파일: 5.py 프로젝트: JohnGinger/aoc
def part_two(input_text):
    return next(run_program(input_text, [5]))
예제 #22
0
import sys
from intcode import run_program

if __name__ == "__main__":

    scan = {}
    for y in range(50):
        for x in range(50):
            program = map(int, open("day19.input", "r").read().split(","))
            out = run_program(program, lambda: (i for i in (x, y)))
            scan[(y, x)] = next(out)

    for y in range(50):
        for x in range(50):
            sys.stdout.write(str(scan[(y, x)]))
        sys.stdout.write("\n")

    print(sum(scan.values()))
예제 #23
0
def main():
    real_input = list(map(int, open("day5.input").read().strip().split(",")))
    result = run_program(real_input)