Exemplo n.º 1
0

with open('input') as program:
    computer = IntCode(program.read().split(','))
computer.memory[0] = 2

screen = Screen(autosolve=True)
value = []
while not computer.is_finished:

    if len(value) == 3:
        screen.add_sprite(*value)
        value = []

    screen.draw()
    out = computer.run()

    if out is StopIteration:
        while True:
            char = screen.read_input().lower()
            try:
                joystick = {'s': 0, 'a': -1, 'd': 1}[char]
                break
            except KeyError:
                pass
        computer.send(joystick)
    else:
        value.append(out)

curses.endwin()
print(screen.score)
Exemplo n.º 2
0
class ASCII:
    """
    Aft Scaffolding Control and Information Interface
    """
    def __init__(self, software):
        self.program = IntCode(software)
        self.map = []
        self.mapstring = ""
        self.intersections = []

    def build_map(self):
        """
        Builds a map from the ASCII output of the IntCode program. Assigns
        results to a map of characters as well as a single string.
        """
        output = self.program.run()
        while output[-1] == 10:
            output.pop()

        output.reverse()
        self.map.append([])
        maprow = 0

        while len(output) > 0:
            char = chr(output.pop())
            self.mapstring += char

            if char == "\n":
                self.map.append([])
                maprow += 1
            else:
                self.map[maprow].append(char)

    def _is_intersection(self, xpos, ypos):
        """
        Check the neighbors of the XY position and return the number of
        neighbors that are a scaffold space.
        """
        results = 0
        for xshift, yshift in [(-1, 0), (1, 0), (0, 1), (0, -1)]:
            if self.map[ypos + yshift][xpos +
                                       xshift] in ["#", "<", ">", "^", "v"]:
                results += 1

        if results == 4:
            return True
        else:
            return False

    def _get_intersections(self):
        """
        Detect all the intersections on the map and populate the list with
        tuples of the XY intersections.
        """
        for ypos in range(1, len(self.map) - 1):
            for xpos in range(1, len(self.map[0]) - 1):
                if self.map[ypos][xpos] == "#":
                    if self._is_intersection(xpos, ypos):
                        self.intersections.append((xpos, ypos))

    def align(self):
        """
        Return the alignment parameter sum.
        """
        self._get_intersections()

        print(self.mapstring)

        sum = 0
        for x, y in self.intersections:
            sum += x * y

        return sum

    def notify(self, routine):
        """
        Primes the robot to perform the notification routine. Sets the initial
        opcode bit, primes the input, and prepares for the run. The run will
        return the amount of dust collected during the routine, which will
        be returned by the function.
        """
        self.program.opcode[0] = 2
        output = self.program.run()

        for line in routine:
            for char in line:
                self.program.add_input(ord(char))
            self.program.add_input(10)

        self.program.add_input(ord("n"))
        self.program.add_input(10)

        output = self.program.run()
        result = output.pop()
        return result
Exemplo n.º 3
0
from sys import path
path.append(path[0] + "/..")
from intcode import IntCode

with open(path[0] + "/input.txt") as f:
    program = [int(x) for x in f.read().strip().split(',')]

part1 = IntCode(program)
part1.memory[1] = 12
part1.memory[2] = 2
part1.run()
print(part1.memory[0])


def bruteForce(x, y, value):
    for i in range(x):
        for j in range(y):
            part2 = IntCode(program)
            part2.memory[1] = i
            part2.memory[2] = j
            part2.run()
            if part2.memory[0] == value:
                return 100 * i + j


print(bruteForce(100, 100, 19690720))
Exemplo n.º 4
0
from sys import path

path.append(path[0] + "/..")
from intcode import IntCode

with open(path[0] + "/input.txt") as f:
    program = [int(x) for x in f.read().strip().split(',')]

part1 = IntCode(program)
part1.run(1)
print(part1.output)
part2 = IntCode(program)
part2.run(2)
print(part2.output)
Exemplo n.º 5
0
from sys import path
path.append(path[0] + "/..")
from intcode import IntCode

with open(path[0] + "/input.txt") as f:
    program = [int(x) for x in f.read().strip().split(',')]

part1 = IntCode(program)
part1.run(1)
print(part1.output)
part2 = IntCode(program)
part2.run(5)
print(part2.output)
Exemplo n.º 6
0
def run_with_replace(data, a, b):
    data[1] = a
    data[2] = b
    m = IntCode(data, level=logging.WARNING)
    m.run()
    return m.ops[0]
Exemplo n.º 7
0
    # Read input
    memory = []
    with open("day21/input.txt") as f:
        for line in f.readlines():
            memory.extend([int(x) for x in line.split(",")])

    # Part 1
    # spring_prog = "OR A J\nAND B J\nAND C J\nNOT J J\nAND D J\nWALK\n"
    # Part 2
    spring_prog = "NOT H J\nOR C J\nAND B J\nAND A J\nNOT J J\nAND D J\nRUN\n"
    output_chars = []

    springbot = IntCode(memory, 0)
    for ch in spring_prog:
        springbot.write_input(str(ord(ch)))

    springbot.run()
    output = int(springbot.read_output())

    while not springbot.is_halted() and output < 256:
        output_chars.append(chr(output))
        springbot.run()
        if not springbot.is_halted():
            output = int(springbot.read_output())

    if output > 255:
        print(f"Damage: {output}")
    else:
        print(f"Hull: {''.join(output_chars)}")
Exemplo n.º 8
0
#!/usr/bin/env python3
from prelude import *
from collections import defaultdict, Counter
from intcode import IntCode
import logging
import networkx as nx

SAMPLE = "3,15,3,16,1002,16,10,16,1,16,15,15,4,15,99,0,0"

if __name__ == "__main__":
    # part1
    m0 = IntCode(SAMPLE.split(","), inputs=[4, 3, 2, 1, 0])
    # m = IntCode(SAMPLE.split(","), inputs=[4])
    # m2 = IntCode(SAMPLE.split(","), inputs=[3])
    # m3 = IntCode(SAMPLE.split(","), inputs=[2])
    # m4 = IntCode(SAMPLE.split(","), inputs=[1])
    # m5 = IntCode(SAMPLE.split(","), inputs=[0])
    m0.run()
    # m.run()
    # m2.run()
    # m3.run()
    # m4.run()
    # m5.run()
    p1 = m0.last_output()
    print(f"2019 7.1 -> {p1}")

    # part2
    # p2 = None
    # print(f"2019 7.2 -> {p2}")

Exemplo n.º 9
0
        return Point(curr_pos.x, curr_pos.y - 1)
    if curr_dir == 1:
        return Point(curr_pos.x + 1, curr_pos.y)
    if curr_dir == 2:
        return Point(curr_pos.x, curr_pos.y + 1)
    if curr_dir == 3:
        return Point(curr_pos.x - 1, curr_pos.y)


grid = defaultdict(lambda: 0)
c = IntCode(program)
curr_pos = Point(0, 0)
curr_dir = 0

while not c.halt:
    output_paint, output_dir = c.run([grid[curr_pos]])
    grid[curr_pos] = output_paint
    curr_dir = next_dir(curr_dir, output_dir)
    curr_pos = next_pos(curr_pos, curr_dir)

print("part 1")
print(len(grid))

print("part 2")

grid = defaultdict(lambda: 0)
c = IntCode(program)
curr_pos = Point(0, 0)
curr_dir = 0
grid[curr_pos] = 1
Exemplo n.º 10
0
def part1(ic: IntCode):
    ic[1] = 12
    ic[2] = 2
    ic.run()
    assert ic[0] == 3058646
    print(ic[0])
Exemplo n.º 11
0
from intcode import IntCode


def rotate(vector, direction):
    degrees = radians({'left': 90, 'right': -90}[direction])
    return (int(vector[0] * cos(degrees) - vector[1] * sin(degrees)),
            int(vector[0] * sin(degrees) + vector[1] * cos(degrees)))


hull = defaultdict(lambda: 0)
robotpos = (0, 0)
robotdirection = (0, 1)

computer = IntCode(stdin.read().split(','))
result = computer.run()

state = 'painting'
while not computer.is_finished:
    if result is StopIteration:
        colour = hull[robotpos]
        computer.send(colour)
    else:
        if state == 'painting':
            hull[robotpos] = result
            state = 'turning'

        elif state == 'turning':
            DIRECTIONS = ('left', 'right')
            robotdirection = rotate(robotdirection, DIRECTIONS[result])
            robotpos = (robotpos[0] + robotdirection[0],
Exemplo n.º 12
0
def navigate(program):
    screen = curses.initscr()
    screen.keypad(True)
    curses.noecho()
    curses.cbreak()

    rows = 80
    cols = 55
    window = curses.newwin(cols, rows, 3, 10)

    # Track path so that we can navigate manually
    # and keep track of the path length
    path = list()
    path_set = set()

    intcode = IntCode(program)
    position = 0
    world = get_world()

    while True:
        char = screen.getch()
        screen.clear()
        screen.refresh()

        if char == 113:
            # q, quit without saving
            break
        elif char == curses.KEY_RIGHT:
            command = RIGHT
        elif char == curses.KEY_LEFT:
            command = LEFT
        elif char == curses.KEY_UP:
            command = UP
        elif char == curses.KEY_DOWN:
            command = DOWN
        else:
            # quit and save the current state
            save_world(world)
            return

        position += directions[command]
        screen.addstr(
            2, 2, f"Position (x={int(position.real)}, y={int(position.imag)})")

        output = intcode.run(command)
        world[position] = items[output]

        if output == 0:
            # cancel forward movement if hit a wall
            position -= directions[command]
        else:
            if position in path_set:
                for pos in reversed(path):
                    if pos == position:
                        break
                    rem_pos = path.pop(-1)
                    path_set.remove(rem_pos)
            else:
                path.append(position)
                path_set.add(position)
            screen.addstr(2, 30, f"Path length = {len(path)}")

        draw(window, world, position)
Exemplo n.º 13
0
def part1(ic: IntCode):
    ic.add_input(1)
    ic.run()
    assert ic.output[0] == 3241900951
Exemplo n.º 14
0
def part2(ic: IntCode):
    ic.add_input(2)
    ic.reset()
    ic.run()
    assert ic.output[0] == 83089
Exemplo n.º 15
0
import os

from intcode import IntCode

if __name__ == "__main__":
    this_dir = os.path.dirname(os.path.abspath(__file__))
    input_path = os.path.join(this_dir, "input.txt")

    with open(input_path) as f:
        raw_code = f.readline()
        intcode = IntCode(raw_code)

        print("Part 1")
        print("Output = {}".format(intcode.run(1)))

        print("Part 2")
        print("Output = {}".format(intcode.run(5)))
Exemplo n.º 16
0
Arquivo: 21.py Projeto: thran/the_code
from intcode import IntCode

memory = list(map(int, open('input.txt').readlines()[0].split(',')))
robot = IntCode(memory)

instructions1 = [
    'NOT C J', 'NOT B T', 'OR T J', 'NOT A T', 'OR T J', 'AND D J', 'WALK', ''
]

instructions = [
    'NOT C J', 'NOT B T', 'OR T J', 'NOT A T', 'OR T J', 'AND D J', 'NOT E T',
    'NOT T T', 'OR H T', 'AND T J', 'RUN', ''
]

output = robot.run(inputs=map(ord, '\n'.join(instructions)))
print(output[-1])
print(''.join(map(chr, output[:-1])))
Exemplo n.º 17
0
    #     intcode.run()

    #     game_data[(x_pos, y_pos)] = tile_id

    # tile_count = [0] * 5
    # for id in game_data.values():
    #     tile_count[id] += 1

    # print(f"Part 1: Count of '2's = {tile_count[2]}")

    # # Part 2
    memory[0] = 2
    intcode = IntCode(memory, 0)
    # intcode.reset()
    game_field = [[" " for _ in range(38)] for _ in range(38)]
    intcode.run()
    while not intcode.is_halted():
        x_pos = int(intcode.read_output())
        intcode.run()
        y_pos = int(intcode.read_output())
        intcode.run()
        tile_id = int(intcode.read_output())
        intcode.run()

        # update_game_data(game_data, x_pos, y_pos, tile_id)
        # draw_game_field(game_data, game_field)
        if (x_pos, y_pos) == (-1, 0):
            print(f"Score: {tile_id}")
        else:
            update_game_data(game_field, x_pos, y_pos, tile_id)
            for y in range(22):
Exemplo n.º 18
0
                pass
        else:
            self.sprites[pos] = tile_id
        if x > self.width:
            self.width = x
        if y > self.height:
            self.height = y

    def draw(self):
        for y in range(self.height + 1):
            for x in range(self.width + 1):
                tile = 0
                if (x, y) in self.sprites:
                    tile = self.sprites[(x, y)]
                print(self.TILE_IDS[tile], end='')
            print()


screen = Screen()
computer = IntCode(stdin.read().split(','))

screen_input = []
value = []
while not computer.is_finished:
    if len(value) == 3:
        screen.add_sprite(*value)
        value = []
    value.append(computer.run())

print(len([True for s in screen.sprites if screen.sprites[s] == 2]))
Exemplo n.º 19
0
        return self.position


field = defaultdict(int)
field[(0, 0)] = 1

bot = PaintingRobot()
memory = [3,8,1005,8,350,1106,0,11,0,0,0,104,1,104,0,3,8,1002,8,-1,10,101,1,10,10,4,10,1008,8,1,10,4,10,102,1,8,29,1006,0,82,1006,0,40,3,8,1002,8,-1,10,101,1,10,10,4,10,1008,8,0,10,4,10,1002,8,1,57,1,102,15,10,1,1005,14,10,1006,0,33,3,8,102,-1,8,10,101,1,10,10,4,10,1008,8,0,10,4,10,102,1,8,90,1,1008,14,10,2,3,19,10,1006,0,35,1006,0,21,3,8,102,-1,8,10,1001,10,1,10,4,10,108,1,8,10,4,10,1002,8,1,125,1,1105,11,10,2,1105,9,10,1,4,1,10,2,1,4,10,3,8,1002,8,-1,10,101,1,10,10,4,10,1008,8,0,10,4,10,101,0,8,164,1006,0,71,3,8,102,-1,8,10,101,1,10,10,4,10,1008,8,0,10,4,10,1002,8,1,189,1006,0,2,1,5,17,10,1006,0,76,1,1002,7,10,3,8,1002,8,-1,10,101,1,10,10,4,10,108,1,8,10,4,10,1001,8,0,224,1,3,5,10,3,8,1002,8,-1,10,101,1,10,10,4,10,108,1,8,10,4,10,101,0,8,250,1,1,20,10,1,102,13,10,2,101,18,10,3,8,1002,8,-1,10,101,1,10,10,4,10,108,0,8,10,4,10,102,1,8,284,2,105,0,10,1,105,20,10,3,8,1002,8,-1,10,101,1,10,10,4,10,1008,8,1,10,4,10,1002,8,1,315,1006,0,88,1,2,4,10,2,8,17,10,2,6,2,10,101,1,9,9,1007,9,1056,10,1005,10,15,99,109,672,104,0,104,1,21102,1,847069688728,1,21101,0,367,0,1106,0,471,21102,386577216404,1,1,21102,378,1,0,1105,1,471,3,10,104,0,104,1,3,10,104,0,104,0,3,10,104,0,104,1,3,10,104,0,104,1,3,10,104,0,104,0,3,10,104,0,104,1,21101,97952923867,0,1,21102,425,1,0,1106,0,471,21101,0,29033143319,1,21102,436,1,0,1105,1,471,3,10,104,0,104,0,3,10,104,0,104,0,21102,1,868410614628,1,21101,0,459,0,1105,1,471,21101,837896909672,0,1,21101,0,470,0,1105,1,471,99,109,2,22102,1,-1,1,21101,40,0,2,21102,502,1,3,21102,492,1,0,1106,0,535,109,-2,2105,1,0,0,1,0,0,1,109,2,3,10,204,-1,1001,497,498,513,4,0,1001,497,1,497,108,4,497,10,1006,10,529,1102,1,0,497,109,-2,2105,1,0,0,109,4,2101,0,-1,534,1207,-3,0,10,1006,10,552,21101,0,0,-3,22101,0,-3,1,22101,0,-2,2,21102,1,1,3,21101,571,0,0,1106,0,576,109,-4,2106,0,0,109,5,1207,-3,1,10,1006,10,599,2207,-4,-2,10,1006,10,599,21202,-4,1,-4,1105,1,667,21202,-4,1,1,21201,-3,-1,2,21202,-2,2,3,21102,1,618,0,1106,0,576,21201,1,0,-4,21101,0,1,-1,2207,-4,-2,10,1006,10,637,21102,0,1,-1,22202,-2,-1,-2,2107,0,-3,10,1006,10,659,21202,-1,1,1,21101,659,0,0,106,0,534,21202,-2,-1,-2,22201,-4,-2,-4,109,-5,2105,1,0]
computer = IntCode(memory)
output = []
inputs = None
first = True

while output != None:
    output = []
    output = computer.run(inputs=inputs, halt_on_output=True, halt_on_missing_input=True)
    inputs = None
    if output is None:
        print("end")
        break
    elif output == "input":
        color = field[bot.whereami()]
        # print(bot.whereami(), color)
        inputs = [color]
    else:
        # print(output)
        if first:   # paint
            field[bot.whereami()] = output
            first = False
        else:   # move
            bot.rotate(output)
Exemplo n.º 20
0
def part2(ic: IntCode):
    ic.add_input(5)
    ic.reset()
    ic.run()
    print(ic.output[0])
    assert ic.output[0] == 513116
Exemplo n.º 21
0
from intcode import IntCode

input_file = open("inputs/day13.txt")
lines = input_file.read().splitlines()
program = [int(i) for i in lines[0].split(",")]

print("part 1")
c = IntCode(program)

output = c.run([])
idx = 0
block_count = 0

while idx < len(output) - 3:
    x, y, tile = output[idx: idx + 3]
    idx += 3
    if tile == 2:
        block_count += 1

print(block_count)

print("part 2")
coined_program = program
coined_program[0] = 2

c = IntCode(program)
Exemplo n.º 22
0
def part1(ic: IntCode):
    ic.add_input(1)
    ic.run()
    print(ic.output[0])
    assert ic.output[0] == 5346030
Exemplo n.º 23
0
from intcode import IntCode

with open('input9.txt') as f:
    ic = IntCode([int(x) for x in f.read().split(',')], in_vals=[2])
    output = []
    while not ic.stopped:
        ic.run()
        output.append(ic.output)
    print(output)
Exemplo n.º 24
0
class Program:
    def __init__(self, raw_code):
        raw_code = "2" + raw_code[1:]
        self._computer = IntCode(raw_code, self._get_input, self._push_output)

    def run(self):
        self._inputs = self._init_inputs()
        self._dust_count = 0
        self._x = 0
        self._y = 0
        self._d = {}
        self._computer.run()
        self._draw(self._d)
        print(f"\nDust = {self._dust_count}\n")

    def _init_inputs(self):
        raw = [
            ["A", "B", "A", "B", "C", "C", "B", "C", "B", "A"],
            ["R", 12, "L", 8, "R", 12],
            ["R", 8, "R", 6, "R", 6, "R", 8],
            ["R", 8, "L", 8, "R", 8, "R", 4, "R", 4],
            ["n"],
        ]
        out = []
        for row in raw:
            for s in row:
                if isinstance(s, int):
                    for o in str(s):
                        out.append(ord(o))
                else:
                    out.append(ord(s))
                out.append(ord(","))
            out.pop()
            out.append(ord("\n"))
        return out

    def _get_input(self):
        nxt = self._inputs.pop(0)
        return nxt

    def _push_output(self, value):
        if value > 128:
            self._dust_count = value
            return
        if value == 10:
            self._y -= 1
            self._x = 0
        else:
            self._d[(self._x, self._y)] = value
            self._x += 1

    def _draw(self, d):
        key = {i: str(chr(i)) for i in range(128)}
        drawer = ConsoleDrawer(key)
        drawer.draw(d)

    def _get_alignment(self):
        out = 0
        scaffolds = set([k for k, v in self._d.items() if v == 35])
        for p in scaffolds:
            neighbors = self._get_neighbors(p)
            if len(scaffolds.intersection(neighbors)) == 4:
                x, y = p
                out += x * y
        return out

    def _get_neighbors(self, p):
        return set([
            (p[0] + 1, p[1]),
            (p[0] - 1, p[1]),
            (p[0], p[1] + 1),
            (p[0], p[1] - 1),
        ])
Exemplo n.º 25
0
def inBeam(program, x, y):
    drone = IntCode(program)
    return drone.run(x, y)[-1] == 1
Exemplo n.º 26
0
        computer._inputs.extend(instruction)

    inventory = [
        'space heater',
        'festive hat',
        'sand',
        'whirled peas',
        'weather machine',
        'mug',
        'easter egg',
        'shell',
    ]
    floor = []

    while True:
        computer.run()

        output = "".join(map(chr, computer._outputs))
        computer._outputs.clear()

        print(output, end='')
        # input_command = make_instruction(input())

        if 'lighter' in output:
            item = random.choice(inventory)
            inventory.remove(item)
            floor.append(item)
            input_command = make_instruction(f'drop {item}\nsouth')
        elif 'heavier' in output:
            item = random.choice(floor)
            floor.remove(item)
Exemplo n.º 27
0
def get_state(x, y):
    # print(x, y)
    system = IntCode(memory.copy())
    return int(system.run(inputs=[x, y])[0])
Exemplo n.º 28
0
def springScript(program, script):
    droid = IntCode(program)
    droid.run()
    script = [ord(x) for x in script]
    droid.run(*script)
    return (droid.output[-1])
Exemplo n.º 29
0
Arquivo: d7b.py Projeto: ocarl/aoc2019
def calc_thrust(inlist, program):
    A = IntCode(program, in_vals=[inlist[0], 0])
    B = IntCode(program, in_vals=[inlist[1]])
    C = IntCode(program, in_vals=[inlist[2]])
    D = IntCode(program, in_vals=[inlist[3]])
    E = IntCode(program, in_vals=[inlist[4]])
    A.run()
    B.input = [inlist[1], A.output]
    B.run()
    C.input = [inlist[2], B.output]
    C.run()
    D.input = [inlist[3], C.output]
    D.run()
    E.input = [inlist[4], D.output]
    E.run()
    A.input = [inlist[0], E.output]
    while not E.stopped:
        A.run()
        B.input = [A.output]
        B.run()
        C.input = [B.output]
        C.run()
        D.input = [C.output]
        D.run()
        E.input = [D.output]
        E.run()
        A.input = [E.output]
    return E.output
Exemplo n.º 30
0
def boost_keycode(program, input_value):
    computer = IntCode(program)
    if input_value:
        computer.queue_input(input_value)
    computer.run()
    return list(computer.output_values)