Exemplo n.º 1
0
    def __init__(self):
        with open("input", "r") as fin:
            program = "".join(fin.readlines())

        self.tiles = " Xv-o"
        self.cpu = IntcodeComputer(program)
        self.screen = dict()
Exemplo n.º 2
0
class Area:
    "Area closest to the ship"

    def __init__(self):
        with open("input") as fhandle:
            self.cpu = IntcodeComputer(fhandle.read().strip())

    @lru_cache
    def tractor(self, pos):
        "Check if a position is within the tractor beam "
        self.cpu.reset()
        self.cpu.step(pos[0])
        self.cpu.step(pos[1])
        try:
            val = self.cpu.step(None)
        except StopIteration:
            pass
        return val

    def countaffected(self, width, height):
        "Count number of points affected by the tractor beam"
        naffected = 0
        for i in range(height):
            for j in range(width):
                if self.tractor((i, j)):
                    naffected += 1

        return naffected
Exemplo n.º 3
0
 def __init__(self, program="input", areamap=None):
     with open(program, 'r') as fin:
         program = "".join(fin.readlines())
     self.brain = IntcodeComputer(program)
     self.pos = (0, 0)
     self.areamap = dict() if areamap is None else areamap
     self.areamap[self.pos] = "."
Exemplo n.º 4
0
 def __init__(self, code="input"):
     self.pos = (0, 0)
     self.direction = 1  # "^"
     self.hull = defaultdict(int)
     with open(code, "r") as fin:
         program = "".join(fin.readlines())
     self.brain = IntcodeComputer(program)
Exemplo n.º 5
0
    def __init__(self):
        super().__init__()

        with open("input", "r") as fin:
            program = fin.read()
        program = "2" + program[1:]  # Insert coin
        self.cpu = IntcodeComputer(program)
        self.ai = ArtificialIntelligence()
Exemplo n.º 6
0
def execute_springscript(springscript, intcode):
    computer = IntcodeComputer(intcode)
    res = computer.execute([ord(c) for c in springscript])

    view_str = ''.join([chr(v) for v in res if v < 256])
    print(view_str)

    print(res[-1])
Exemplo n.º 7
0
def main():
    with open("input23") as f:
        intcode = [int(v) for v in f.read().split(',')]

        # Init 50 computers
        computersbyaddress = {}
        for i in range(50):
            computer = IntcodeComputer(intcode)
            # Set computer address
            computer.inputs = [i]

            computersbyaddress[i] = computer

        # Run network IO for each computer one by one

        natx = None
        naty = None
        previousnatysent = None
        while True:
            idle = True
            for computer in computersbyaddress.values():
                # add -1 to input if there's nothing in queue
                if not computer.inputs:
                    computer.inputs.append(-1)
                else:
                    idle = False

                output = computer.execute([])
                while len(output) >= 3:
                    idle = False
                    # get packet sent by this computer
                    address = output.pop(0)
                    x = output.pop(0)
                    y = output.pop(0)

                    # Nat management
                    if address == 255:
                        print("packet sent to nat(255): {} {}".format(x, y))
                        natx = x
                        naty = y

                    else:
                        # Put it in the target computer queue
                        computersbyaddress[address].inputs.extend([x, y])

            if idle:
                # Idle network, nat send store packet to addresse 0
                computersbyaddress[0].inputs.extend([natx, naty])
                if previousnatysent == naty:
                    print(
                        "sending same y value twice in a row: {}".format(naty))
                    return

                previousnatysent = naty
Exemplo n.º 8
0
class Robot:
    "Hull painting robot"

    def __init__(self, code="input"):
        self.pos = (0, 0)
        self.direction = 1  # "^"
        self.hull = defaultdict(int)
        with open(code, "r") as fin:
            program = "".join(fin.readlines())
        self.brain = IntcodeComputer(program)

    def step(self):
        "Input 0 if black or 1 if white output color to paint and new direction"
        col = self.hull[self.pos]

        self.hull[self.pos] = self.brain.step(col)

        clockwise = self.brain.step(col)
        if clockwise:
            self.direction = self.direction + 1 if self.direction < 3 else 0
        else:
            self.direction = self.direction - 1 if self.direction > 0 else 3

        direction = DIRECTIONS[self.direction]
        if direction == "<":
            self.pos = (self.pos[0] - 1, self.pos[1])
        elif direction == "^":
            self.pos = (self.pos[0], self.pos[1] - 1)
        elif direction == ">":
            self.pos = (self.pos[0] + 1, self.pos[1])
        elif direction == "v":
            self.pos = (self.pos[0], self.pos[1] + 1)

    def run(self):
        "Run robot"
        try:
            while True:
                self.step()
        except StopIteration:
            pass

    def render(self, width=43, height=6, offset=0):
        "Show painted surface"
        field = [["x" for _ in range(width)] for _ in range(height)]
        for pos, col in self.hull.items():
            field[pos[1] + offset][pos[0] + offset] = '#' if col else "."
            if pos == self.pos:
                field[pos[1] + offset][pos[0] +
                                       offset] = DIRECTIONS[self.direction]

        print("\n".join(["".join(row) for row in field]))
Exemplo n.º 9
0
class Robot:
    "Repair droid"

    def __init__(self, program="input", areamap=None):
        with open(program, 'r') as fin:
            program = "".join(fin.readlines())
        self.brain = IntcodeComputer(program)
        self.pos = (0, 0)
        self.areamap = dict() if areamap is None else areamap
        self.areamap[self.pos] = "."

    def clone(self):
        "Create a new robot clone"
        other = Robot()
        other.brain = self.brain.copy()
        other.pos = deepcopy(self.pos)
        other.areamap = deepcopy(self.areamap)

        return other

    def isexplored(self, direction):
        "Check if a position has been explored"
        if peek(self.pos, direction) in self.areamap:
            return True
        return False

    def move(self, direction):
        "Move to a new position"
        self.pos = peek(self.pos, direction)

    def step(self, direction):
        "Take one step in a direction"
        retval = self.brain.step(direction)
        oldpos = self.pos
        self.move(direction)
        if retval == 0:
            self.areamap[self.pos] = "#"
            self.pos = oldpos
        elif retval == 1:
            self.areamap[self.pos] = "."
        elif retval == 2:
            self.areamap[self.pos] = "O"
        else:
            raise Exception("Error in step")

    def show(self, offset=20):
        "Print situation"
        printmap = deepcopy(self.areamap)
        printmap[self.pos] = "X"
        render(printmap, offset=offset)
Exemplo n.º 10
0
class ArcadeGame:
    "Arcade cabinet"

    def __init__(self):
        with open("input", "r") as fin:
            program = "".join(fin.readlines())

        self.tiles = " Xv-o"
        self.cpu = IntcodeComputer(program)
        self.screen = dict()

    def run(self):
        "Simulate arcade cabinet"
        try:
            nsteps = 0
            while True:
                nsteps += 1
                xpos = self.cpu.step(0)
                ypos = self.cpu.step(0)
                what = self.cpu.step(0)
                self.screen[(xpos, ypos)] = what
        except StopIteration:
            pass
        return nsteps

    def score(self):
        "Return player score"
        return self.screen.get((-1, 0), None)

    def render(self, width=40, height=40):
        "Show screen"
        screen = [[' ' for _ in range(width)] for _ in range(height)]
        score = 0
        for (x, y), tile in self.screen.items():
            if x == -1 and y == 0:
                score = tile
            else:
                screen[y][x] = self.tiles[tile]
        print("\n".join(["".join(row) for row in screen]))
        print("Score: " + str(score))
Exemplo n.º 11
0
class ArcadeGameAI(ArcadeGame):
    "Arcade cabinet"

    def __init__(self):
        super().__init__()

        with open("input", "r") as fin:
            program = fin.read()
        program = "2" + program[1:]  # Insert coin
        self.cpu = IntcodeComputer(program)
        self.ai = ArtificialIntelligence()

    def run(self):
        "Simulate arcade cabinet"
        try:
            while True:
                xpos = self.cpu.step(self.ai.command)
                ypos = self.cpu.step(self.ai.command)
                what = self.cpu.step(self.ai.command)
                self.ai.update(xpos, what)

                self.screen[(xpos, ypos)] = what
        except StopIteration:
            pass
Exemplo n.º 12
0
class SpringBot:
    "Springdroid"

    def __init__(self, interactive=False):
        with open("input") as fhandle:
            self.cpu = IntcodeComputer("".join(fhandle.readlines()),
                                       interactive)

    def runprogram(self, instructions):
        "Run instructions on cpu"
        self.cpu.reset()
        try:
            for char in instructions.strip():
                self.cpu.step(ord(char))
            while True:
                self.cpu.step(10)
        except StopIteration:
            pass

        return self.cpu.outval
Exemplo n.º 13
0
 def __init__(self, *, program, settings):
     self.computers = [IntcodeComputer(program)
                       for _ in range(len(settings))]
     for computer, setting in zip(self.computers, settings):
         computer.inqueue.append(setting)
Exemplo n.º 14
0
 def __init__(self):
     with open("input", 'r') as fhandle:
         program = fhandle.read().strip()
         self.map = None
         self.brain = IntcodeComputer(program)
Exemplo n.º 15
0
class VacuumRobot:
    "ASCIIRobot"

    def __init__(self):
        with open("input", 'r') as fhandle:
            program = fhandle.read().strip()
            self.map = None
            self.brain = IntcodeComputer(program)

    def getmap(self):
        "Explore area to find alignment parameters"
        view = []
        try:
            while True:
                char = chr(self.brain.step(None))
                view.append(char)
        except StopIteration:
            pass

        view = list("".join(view).strip().split("\n"))
        width = len(view[0])
        height = sum(1 for row in view if len(row) == len(view[0]))
        assert height == len(view)
        alignpar = 0

        for i in range(len(view)):
            for j in range(len(view[0])):
                if view[i][j] == "#":
                    neigbors = 0
                    neigbors += 1 if i > 0 and view[i - 1][j] == "#" else 0
                    neigbors += 1 if i < height - 1 and view[
                        i + 1][j] == "#" else 0
                    neigbors += 1 if j > 0 and view[i][j - 1] == "#" else 0
                    neigbors += 1 if j < width - 1 and view[i][j +
                                                               1] == "#" else 0
                    if neigbors == 4:
                        alignpar += i * j

        self.map = view
        return alignpar

    def showmap(self):
        "print map from viewport"
        view = self.getmap()
        print("\n".join(["".join(row) for row in view]))

    def execute(self, instructions):
        for instruction in instructions:
            self.brain.step(ord(instruction))

    def override(self, program, funcA, funcB, funcC, video="y"):
        self.brain.code[0] = 2

        # Main Program
        self.execute(program)

        # Function A
        self.execute(funcA)

        # Function B
        self.execute(funcB)

        # Function C
        self.execute(funcC)

        # Video
        self.execute(video + "\n")

        while True:
            self.brain.step(0)
Exemplo n.º 16
0
                    line += "0"
                elif val == 0:
                    line += " "

            else:
                line += " "

        print(line)

    print(score)


with open("input13") as f:
    intcode = [int(v) for v in f.read().split(',')]

    computer = IntcodeComputer(intcode)
    computer.write(0, 2)

    screen = {}
    score = 0
    cmd = 0
    while not computer.terminated:
        res = computer.execute([cmd])

        for i in range(0, len(res), 3):
            x = res[i]
            y = res[i + 1]
            val = res[i + 2]

            if x == -1 and y == 0:
                score = val
Exemplo n.º 17
0
 def __init__(self):
     with open("input") as fhandle:
         self.cpu = IntcodeComputer(fhandle.read().strip())
Exemplo n.º 18
0
from intcodecomputer import IntcodeComputer

with open("input11") as f:
    intcode = [int(v) for v in f.read().split(',')]

    computer = IntcodeComputer(intcode)

    pos = (0, 0)
    orientation = 0
    # part 1
    # whitepanels = set()
    # part 2
    whitepanels = {(0, 0)}
    paintedpanels = set()

    while not computer.terminated:
        currentpanelcolor = 1 if pos in whitepanels else 0
        color, turn = computer.execute([currentpanelcolor])

        paintedpanels.add(pos)

        if color == 1:
            whitepanels.add(pos)
        else:
            whitepanels.discard(pos)

        if turn == 1:
            orientation = (orientation + 1) % 4
        else:
            orientation = (orientation - 1) % 4
Exemplo n.º 19
0
def isonbeam(x, y, intcode):
    computer = IntcodeComputer(intcode)
    res = computer.execute([x, y])
    return res[0]
Exemplo n.º 20
0
                                   or result < best_result):
            best_result = result

        computer.loadstate(before_move_state)

    if best_result is not None:
        best_result += 1

    return best_result


with open("input15") as f:

    intcode = [int(v) for v in f.read().split(',')]

    computer = IntcodeComputer(intcode)

    # part 1
    steps = step_required(computer, (0, 0), [])
    print("{} steps to oxygen".format(steps))

    # part 2
    propagated = True
    minutes = -1
    while propagated:
        propagated = False
        newoxygen = set()
        for pos in oxygen:
            for direction in range(1, 5):
                targetpos = move(pos, direction)
                if targetpos not in walls and targetpos not in oxygen:
Exemplo n.º 21
0
def main():
    with open("input17") as f:

        intcode = [int(v) for v in f.read().split(',')]

        computer = IntcodeComputer(intcode)

        res = computer.execute([])

        view_str = ''.join([chr(v) for v in res])

        lines = view_str.splitlines()

        for line in lines:
            print(line)

        position = None
        orientation = None

        # Part 1
        total = 0
        for y, line in enumerate(lines):
            for x, char in enumerate(line):
                try:
                    if (char == '#' and lines[y - 1][x] == '#'
                            and lines[y + 1][x] == '#'
                            and lines[y][x - 1] == '#'
                            and lines[y][x + 1] == '#'):
                        total += x * y
                except IndexError:
                    pass

                if char in orientations:
                    position = (x, y)
                    orientation = char

        print(total)

        # Part 2
        # Find path
        commands = []
        while True:
            tx, ty = calculatetargetcoords(position, orientation)
            try:
                target = lines[ty][tx]
            except IndexError:
                target = None
                pass

            if target == "#":
                commands.append('1')
                position = (tx, ty)
            else:
                for turn in ['L', 'R']:
                    targetorienation = calculatetargetorientation(
                        orientation, turn)
                    tx, ty = calculatetargetcoords(position, targetorienation)
                    try:
                        target = lines[ty][tx]
                    except IndexError:
                        target = None
                        pass

                    if target == "#":
                        # This direction looks promising
                        commands.append(turn)
                        orientation = targetorienation
                        break
                else:
                    # Could not find anywhere to get next, must be the end
                    break

        commands = list(aggregatesones(commands))

        # Attempt to divide the commands in 3 routines covering everything
        routines = findpatternscoverall(commands, [False] * len(commands), 3)

        routinecalls = []
        i = 0
        while i < len(commands):
            # Find routine to use
            for routineid, routine in enumerate(routines):
                if commands[i:i + len(routine)] == routine:
                    routinecalls.append(['A', 'B', 'C'][routineid])
                    i += len(routine)
                    break
            else:
                raise Exception("Could not find routine")

        # Add robot subroutines to call
        robotinputs = commandstostring(routinecalls) + "\n"

        # Add commands for each subroutines
        for routine in routines:
            robotinputs += commandstostring(routine) + "\n"

        # Add continous video feed 'no'
        robotinputs += "n\n"

        print(robotinputs)

        # Send this to the robot
        computer = IntcodeComputer(intcode)
        computer.write(0, 2)
        res = computer.execute([ord(c) for c in robotinputs])

        view_str = ''.join([chr(v) for v in res[:-1]])
        print(view_str)

        # Final ouput value
        print(res[-1])
Exemplo n.º 22
0
from intcodecomputer import IntcodeComputer

with open("input9") as f:
    intcode = [int(v) for v in f.read().split(',')]

    computer = IntcodeComputer(intcode)

    print(computer.execute([2]))
Exemplo n.º 23
0
 def __init__(self, interactive=False):
     with open("input") as fhandle:
         self.cpu = IntcodeComputer("".join(fhandle.readlines()),
                                    interactive)