Beispiel #1
0
def painted_panels(intcode_program: list[int], starting_input: int,
                   get_image_meta: bool) -> dict[Position, int]:
    computer = IntcodeComputer(intcode_program,
                               inputs=[starting_input],
                               return_output=True)
    if get_image_meta:
        xmin = xmax = ymin = ymax = 0
    panels_painted = {}
    position: Position = (0, 0)
    pointing = "U"
    while True:
        color = computer.run()
        if computer.halted():
            break
        panels_painted[position] = color
        if get_image_meta:
            x, y = position
            xmin = min(xmin, x)
            xmax = max(xmax, x)
            ymin = min(ymin, y)
            ymax = max(ymax, y)
        direction = computer.run()
        position, pointing = move_robot(position, direction, pointing)
        computer.append_inputs(panels_painted.get(position, 0))
    if get_image_meta:
        return panels_painted, (xmin,
                                ymax), (abs(xmin) + xmax), (abs(ymin) + ymax)
    else:
        return panels_painted
Beispiel #2
0
def play(screen, program):
    if RENDER_GAME:
        curses.curs_set(0)
        y_max = 0
    computer = IntcodeComputer(program,
                               return_output=True,
                               return_before_input=True)
    current_score = 0
    game_tiles = {}
    while True:
        output = computer.run()
        if output is computer.sentinel_return:
            bx, px = ball_and_paddle_x(game_tiles)
            computer.append_inputs(-1 if bx < px else 1 if bx > px else 0)
            x = computer.run()
        else:
            x = output
        y = computer.run()
        tile_id = computer.run()
        if computer.halted():
            break
        if x == -1 and y == 0:
            current_score = tile_id
            if RENDER_GAME:
                screen.addstr(y_max + 2, 0, f"Score => {current_score}")
                screen.refresh()
        else:
            game_tiles[(x, y)] = tile_id
            if RENDER_GAME:
                y_max = max(y_max, y)
                screen.addstr(y, x, COMPONENTS[tile_id])
                screen.refresh()
                sleep(FRAME_RATE)
    return current_score
Beispiel #3
0
def solution1(data: List[int], noun=12, verb=2) -> int:
    computer = IntcodeComputer(data)
    computer.registers[1] = noun
    computer.registers[2] = verb
    while not computer.halted:
        computer.run()
    return computer.registers[0]
Beispiel #4
0
def main(data):
    ic = IntcodeComputer(data, init=2)
    ic.run()
    while True:
        try:
            print(ic.output)
        except Empty:
            break
Beispiel #5
0
def main(data):
    for i in range(100):
        for j in range(100):
            ic = IntcodeComputer(data)
            ic.code[1] = i
            ic.code[2] = j
            ic.run()
            if ic.code[0] == OUTPUT:
                return i, j
Beispiel #6
0
def solution1(data: List[int]) -> int:
    computer = IntcodeComputer(data)
    computer.send(1)
    while not computer.halted:
        computer.run()
    result = 0
    while result == 0:
        result = computer.read()
    return result
Beispiel #7
0
def main(data):
    for system_id in (1, 5):
        ic = IntcodeComputer(data, init=system_id)
        ic.run()
        while True:
            try:
                print(ic.output)
            except Empty:
                break
Beispiel #8
0
def main(data):
    powers = []
    for perm in permutations(range(5)):
        q = LifoQueue()
        q.put(0)
        for phase in perm:
            ic = IntcodeComputer(data, in_queue=q, out_queue=q)
            q.put(phase)
            ic.run()
        powers.append(q.get())
    print(max(powers))
Beispiel #9
0
def count_block_tiles(program):
    computer = IntcodeComputer(program, return_output=True)
    count = 0
    while True:
        computer.run()
        computer.run()
        tile_id = computer.run()
        if computer.halted():
            break
        if tile_id == 2:
            count += 1
    return count
Beispiel #10
0
def solution1(data: List[int]) -> int:
    best = float("-inf")
    for phase_setting in permutations(range(5), 5):
        result = 0
        for amplifier in phase_setting:
            computer = IntcodeComputer(data)
            computer.send(amplifier)
            computer.send(result)
            while not computer.halted:
                computer.run()
            result = computer.read()
        best = max(best, result)
    return best
Beispiel #11
0
def Day02(program_file, part1=True, target=None):
    if part1:
        VM = IntcodeComputer(program_file)
        VM.override({1: 12, 2: 2})
        VM.run()
        return VM.P[0]

    for noun in range(100):
        for verb in range(100):
            VM = IntcodeComputer(program_file)
            VM.override({1: noun, 2: verb})
            VM.run()
            if VM.P[0] == target:
                return (100 * noun) + verb
Beispiel #12
0
def Day05(program_file, input, output=False):
    VM = IntcodeComputer(program_file, input)
    while not VM.halted:
        result = VM.run()
        if result is not None:
            diagnostic_code = result
    return diagnostic_code
Beispiel #13
0
def runner(seq):
    a = IntcodeComputer(INPUT, [0, seq[0]])
    b = IntcodeComputer(INPUT, [seq[1]])
    c = IntcodeComputer(INPUT, [seq[2]])
    d = IntcodeComputer(INPUT, [seq[3]])
    e = IntcodeComputer(INPUT, [seq[4]])
    results = []
    while 'HALTED' not in results:
        a_result = a.run()
        b.addInput(a_result)
        b_result = b.run()
        c.addInput(b_result)
        c_result = c.run()
        d.addInput(c_result)
        d_result = d.run()
        e.addInput(d_result)
        e_result = e.run()
        a.addInput(e_result)
        results = results + [a_result, b_result, c_result, d_result, e_result]
    return max([x for x in results if x != 'HALTED'])
Beispiel #14
0
def Day21(program_file, part=1, debug=False):

    def get_input():
        """Return next queued ASCII value as input to VM."""
        ch = Q.popleft()
        if debug:
            print(ch, end='', flush=True)
        return ord(ch)

    # Springscripts deduced logically
    S = {
        1: [
            "NOT C T",
            "OR D J",
            "AND T J",
            "NOT A T",
            "OR T J",
            "WALK"
        ],
        2: [
            "NOT H J",
            "OR C J",
            "AND B J",
            "AND A J",
            "NOT J J",
            "AND D J",
            "RUN"
        ]
    }

    # Queue springscript instructions
    Q = deque()
    for instr in S[part]:
        [Q.append(ch) for ch in instr]
        Q.append("\n")

    # Neater output
    if debug:
        print()

    # Continuously run until non-ASCII output returned
    VM = IntcodeComputer(program_file, input=get_input)
    while not VM.halted:
        out = VM.run()
        if out not in range(128):
            return out
        if debug:
            print(chr(out), end='', flush=True)
Beispiel #15
0
def Day13(program_file, grid_init, part2=False, plot=False):

    def get_joystick():
        """Simple AI tracking the ball position with the paddle."""
        return np.sign(ball - paddle)

    # Set up grid (determined from wall positions)
    R, C = grid_init
    G = [[0 for _ in range(C)] for _ in range(R)]

    # Initialise Intcode program
    if part2:
        VM = IntcodeComputer(program_file, input=get_joystick)
        VM.override({0: 2})
        # Buffer for score display at the top of screen
        row_buffer = 2
    else:
        VM = IntcodeComputer(program_file)
        row_buffer = 0

    # Carry on receiving output from program until it halts
    while True:
        c, r, tile = [VM.run() for _ in range(3)]
        if c == -1:
            score = tile
        if VM.halted:
            break
        elif tile == 3:
            paddle = c    # Save paddle x-position
        elif tile == 4:
            ball = c      # Save ball x-position
        G[r + row_buffer][c] = tile

    # Matplotlib plot
    if plot:
        plt.figure()
        plt.imshow(G, cmap='gist_stern')
        plt.axis('off')
        if part2:
            plt.text(
                42.2, 0.6, "Score: " + str(score), fontsize=9, family='Consolas',
                color='white', horizontalalignment='right'
            )

    if part2:
        return score
    return sum(x.count(2) for x in G)
Beispiel #16
0
    def solve(self):
        if self.routine is not None:
            self.queue_auto()

        VM = IntcodeComputer(self.program_file, input=self.get_input)
        encounter = ""
        while not VM.halted:
            out = VM.run()
            if out is not None:
                encounter += (out := chr(out))
                if self.output:
                    print(out, end='', flush=self.routine is None)
                if out == '?':
                    self.current_room = re.findall(self.ROOM_SEARCH,
                                                   encounter).pop()
                    self.last = encounter.split(self.CMD)[-2]
        password = re.findall(r'\d+', encounter).pop()
        return int(password)
Beispiel #17
0
    def start_job(self, intCode):
        comp = IntcodeComputer(intCode)
        while True:
            if not [self.botPosX, self.botPosY] in self.painted:
                self.painted.append([self.botPosX, self.botPosY])

            currColor = self.paint[self.botPosX][self.botPosY]
            res = comp.run(currColor, False)
            if len(res) == 0:
                return
            color = res[0]
            turn = res[1]
            self.paint[self.botPosX][self.botPosY] = str(color)

            self.turn_bot(turn)

            if self.botFace == 0:
                self.botPosX += 1
            elif self.botFace == 1:
                self.botPosY += 1
            elif self.botFace == 2:
                self.botPosX -= 1
            else:
                self.botPosY -= 1
Beispiel #18
0
canvas = np.zeros((39, 20), dtype='int')
fig, ax = plt.subplots(num=0)
im = ax.imshow(canvas.T, vmin=0, vmax=4)

paddle_position = 19
target_paddle_position = 19
ball_position = 17
ball_old_position = 17
ball_direction = 1
score = 0
next_input = 0

ic = IntcodeComputer(allow_pausing=True)
ic.code[0] = 2
ic.run(0)
ic.resume(0)
ic.resume(0)
while ic.continue_flag:
    ic.resume(next_input)
    ic.resume(next_input)
    ic.resume(next_input)
    x, y, t = ic.output[-3:]
    if x == -1:
        score = t
        print("score = ", score)
        ax.imshow(canvas.T)
        fig.canvas.draw()
        plt.pause(.01)

        continue
def query_a_point(x, y):
    comp = IntcodeComputer(instr_list)
    comp.stdin = (x, y)
    comp.run()
    return comp.stdout
Beispiel #20
0
    out = '\n'.join(lines) + '\n'
    out += '█' * 37 + '\n'
    out += ' ' * 12 + 'Score: %5d\n\n' % score
    # os.system('clear')
    sys.stdout.write(out)
    sys.stdout.flush()
    time.sleep(0.02)


with open('input.txt', 'r') as f:
    program_code = [int(x) for x in f.read().split(',')]
    computer = IntcodeComputer(debug=False)
    inputs = deque()

    # Part 1
    computer.run(program_code, inputs)
    outputs = computer.outputs
    tiles = process_outputs(outputs)
    num_blocks = sum([1 for x in tiles if x[2] == 2])
    print('Num blocks:', num_blocks)
    assert num_blocks == 344

    # Part 2
    program_code[0] = 2
    computer.initialize(program_code, inputs)

    score = 0
    while True:
        computer.reset_outputs()
        done = computer.execute()
        outputs = computer.outputs
Beispiel #21
0
from itertools import permutations

import numpy as np
from intcode import IntcodeComputer

possibilities = permutations([0, 1, 2, 3, 4])

outputs = []
for phases in possibilities:
    ph_A, ph_B, ph_C, ph_D, ph_E = phases
    amp_A = IntcodeComputer('input_day07.txt')
    amp_B = IntcodeComputer('input_day07.txt')
    amp_C = IntcodeComputer('input_day07.txt')
    amp_D = IntcodeComputer('input_day07.txt')
    amp_E = IntcodeComputer('input_day07.txt')

    amp_A.run([ph_A, 0])
    amp_B.run([ph_B, amp_A.output[0]])
    amp_C.run([ph_C, amp_B.output[0]])
    amp_D.run([ph_D, amp_C.output[0]])
    amp_E.run([ph_E, amp_D.output[0]])

    outputs.append(amp_E.output[0])

print(max(outputs))
Beispiel #22
0
from intcode import IntcodeComputer

with open('day-9-input.txt') as f:
    program = [int(x) for x in f.readline().strip().split(',')]

computer = IntcodeComputer()

# Part 1
outputs = computer.run(program, [1])
print(outputs)

# Part 2
outputs = computer.run(program, [2])
print(outputs)
Beispiel #23
0
while running:
    if show:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False

    if not fully_explored:
        new_position = (position[0] + dx[directions_i],
                        position[1] + dy[directions_i])
        if new_position == origin:
            fully_explored = True
            walkable = {k for k, v in world.items() if v == "walkable"}

        status = droid.run([directions[directions_i]])
        if status == 0:
            directions_i = (directions_i + 1) % 4
            world[new_position] = "wall"
        elif status == 1 or status == 2:
            if new_position in world:
                if not found_oxygen_system:
                    path.pop()
            else:
                world[new_position] = "walkable"
                if status == 2:
                    contains_oxygen.add(new_position)
                    check_neighbors.add(new_position)
                    found_oxygen_system = True
                if not found_oxygen_system:
                    path.append(new_position)
Beispiel #24
0
def solution2(data: List[int]) -> int:
    computer = IntcodeComputer(data)
    computer.send(5)
    while not computer.halted:
        computer.run()
    return computer.read()
Beispiel #25
0
from intcode import IntcodeComputer

# Part 1
with open('day-2-input.txt') as f:
    program = [int(x) for x in f.readline().strip().split(',')]
program[1] = 12
program[2] = 2

computer = IntcodeComputer()
computer.run(program)
result = computer.memory[0]
print(result)

# for Part 2, see day-2-notes.txt
import numpy as np
from intcode import IntcodeComputer, RunState
from pylab import imshow, show, figure, pause

with open('day17-input.txt', 'r') as f:
    instr_list = [int(w) for w in f.readline().split(',')]
instr_list = np.array(instr_list)
instr_list[0] = 2

comp = IntcodeComputer(instr_list)
comp.run()


def print_out(intcode_comp):
    while True:
        c = intcode_comp.stdout
        if c is not None:
            if c < 128:
                print(chr(c), end='')
            else:
                print('score:', c)
        else:
            break


print_out(comp)
"""
..............#####................................
..............#...#................................
....#############.#................................
....#.........#.#.#................................
Beispiel #27
0
import numpy as np
from intcode import IntcodeComputer, RunState
from pylab import imshow, show, figure, pause
import sys

with open('day21-input.txt', 'r') as f:
    instr_list = [int(w) for w in f.readline().split(',')]

comp = IntcodeComputer(instr_list)
out = comp.run()


def feed(s):
    for c in s:
        comp.append_input(ord(c))
    comp.run()
    ret = []
    while True:
        c = comp.get_stdout()
        if c != None:
            ret.append(c)
        else:
            break
    return ret


if sys.argv[1] == '1':
    res = feed("""OR A T
AND B T
AND C T
NOT T J
Beispiel #28
0
def Day15(program_file, grid_init, part1=True, plot=None):

    # Constants
    WALL = 0
    TRAVERSED = 1
    OXYGEN = 2
    DROID = 3
    UNEXPLORED = 4
    CLOCKWISE = {
        1: 4,
        2: 3,
        3: 1,
        4: 2
    }
    ANTICLOCKWISE = {v: k for k, v in CLOCKWISE.items()}
    DR, DC = [None, -1, 1, 0, 0], [None, 0, 0, -1, 1]

    def get_command(movement_command, status_code):
        """Determine next input command, N (1), S (2), W (3), E (4)."""
        if movement_command is None:
            return 1
        if status_code == WALL:
            return ANTICLOCKWISE[movement_command]
        if status_code == TRAVERSED:
            return CLOCKWISE[movement_command]
        else:
            assert status_code == OXYGEN
            return 1

    def get_input():
        """Function used as input to Intcode VM."""
        return movement_command

    def draw_grid(G, style='ascii'):
        """
        Draw a representation of G in a given style.

        Arguments:
          G -- grid to draw
          style -- method of visualisation, two accepted string values:
            'ascii':  ASCII art
            'mpl':    Matplotlib plot
        """

        # ASCII art mapping
        ASCII = {
            WALL: "#",
            TRAVERSED: ".",
            OXYGEN: "O",
            DROID: "D",
            UNEXPLORED: " "
        }

        # Draw ASCII art
        if style.lower() == 'ascii':
            grid = "\n"
            for r in G:
                for c in r:
                    grid += ASCII[c]
                grid += "\n"
            print(grid)
            return None

        # Matplotlib plot
        assert style.lower() == 'mpl', f"Invalid plot style: {style}"
        plt.figure(figsize=(8, 8))
        cmap = ListedColormap([
            'xkcd:dark indigo',        # Walls
            'white',                   # Traversed
            'crimson',                 # Oxygen
            'xkcd:azure',              # Droid
            'black'                    # Unexplored
        ])
        plt.imshow(G, cmap=cmap)
        plt.axis('off')
        return None

    # Initialise grid
    R, C = grid_init
    r = r0 = R // 2 + 1
    c = c0 = (C // 2) + 1
    G = [[UNEXPLORED for _ in range(C)] for _ in range(R)]
    G[r][c] = DROID
    movement_command = None
    status_code = None
    commands = 0
    visited = {(r0, c0): commands}
    # Part 2
    longest = 0
    oxygen_found = False
    oxygen_path = {}

    # Initialise Intcode program
    VM = IntcodeComputer(program_file, input=get_input)

    while not VM.halted:
        movement_command = get_command(movement_command, status_code)
        dr, dc = DR[movement_command], DC[movement_command]
        status_code = VM.run()
        # Process output
        if status_code == WALL:
            # Hit a wall, droid cannot move in given direction
            G[r + dr][c + dc] = WALL
            continue
        # Droid successfully moved in the given direction
        if G[r][c] != OXYGEN:
            G[r][c] = TRAVERSED
        r += dr
        c += dc
        # Update visited
        if (r, c) not in visited:
            commands += 1
            visited[(r, c)] = commands
        else:
            # Backtracking after hitting dead-end
            commands -= 1
        # Update oxygen path
        if oxygen_found and (r, c) not in oxygen_path:
            longest += 1
            oxygen_path[(r, c)] = longest
        elif oxygen_found:
            longest -= 1
        # Successful movement status codes
        if status_code == OXYGEN:
            G[r][c] = OXYGEN
            if part1:
                if plot:
                    G[r0][c0] = DROID
                    draw_grid(G, style=plot)
                return commands
            oxygen_found = True
        else:
            assert status_code == TRAVERSED
            G[r][c] = DROID
        # Halt if we're back at the starting position
        if (r, c) == (r0, c0):
            break

    if plot:
        draw_grid(G, style=plot)
    return max(oxygen_path.values())
Beispiel #29
0
# https://adventofcode.com/2019/day/2

import itertools

from intcode import IntcodeComputer

with open("../../input/2019-02-input.txt") as file:
    program = [int(i) for i in file.read().split(",")]

# part 1
program[1] = 12
program[2] = 2
computer = IntcodeComputer(program)
computer.run()
print(computer.intcode[0])  # 3101844

# part 2
target = 19690720
for noun, verb in itertools.product(range(100), repeat=2):
    computer.original_intcode[1] = noun
    computer.original_intcode[2] = verb
    computer.reset()
    computer.run()
    if computer.intcode[0] == target:
        break
print(100 * noun + verb)  # 8478
Beispiel #30
0
            break
        else:
            print('error')
            return 0
    return intcode


def process_opcode(opcode):
    opcode = str(opcode)
    mode = opcode[-2:]
    p_modes = []
    for p in range(3, 6):
        if p <= len(opcode):
            p_modes.append(1 if opcode[-p] == '1' else 0)
        else:
            p_modes.append(0)
    return opcode_instructions[int(mode)], [
        parameter_modes[p] for p in p_modes
    ]


code = process_code(intcode)
print(code)

from intcode import read_intcode_input_file, IntcodeComputer

code = read_intcode_input_file('input.txt')
IC = IntcodeComputer(code, [])
code = IC.run()
print(code)