Beispiel #1
0
def part1(data):
    print(data)

    grid = []
    size = 50
    for j in range(size):
        row = []
        for i in range(size):
            row.append(".")
        grid.append(row)

    for j in range(size):
        for i in range(size):
            print("inputs", i, j)
            # in this problem, the intcoder only runs once for each input
            intcoder = Intcode(deepcopy(data), [i, j], debug=False)
            intcoder.run()
            print("output", intcoder.output)
            if intcoder.output[0] == 1:
                grid[j][i] = "#"

    print_2d_grid(grid)
    count = 0
    for row in grid:
        for item in row:
            if item == "#":
                count += 1

    print("count", count)
def run_tests():
    test1 = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
    assert list(Intcode(test1).run()) == test1
    test2 = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
    assert len(str(list(Intcode(test2).run())[0])) == 16
    test3 = [104, 1125899906842624, 99]
    assert list(Intcode(test3).run())[0] == 1125899906842624
Beispiel #3
0
def part1(data):
    print(data)
    data[1] = 12
    data[2] = 2

    intcoder = Intcode(data)
    intcoder.run()

    print("answer", intcoder.state[0])
Beispiel #4
0
def part1(data):
    print(data)
    intcoder = Intcode(data, [0])
    intcoder.run()
    output = intcoder.output
    output = chunkIt(output, len(output)/3)
    numBlocks = 0
    for tile in output:
        if tile[2] == 2:
             numBlocks +=1
    print(numBlocks)
Beispiel #5
0
def part2(data):

    asciiInput = ""

    # PART 1
    # if not (A or B or C) and D then jump
    # J if A is ground
    asciiInput += "NOT A J\n"
    # T if B is ground
    asciiInput += "NOT B T\n"

    # J if A or B is ground
    asciiInput += "OR T J\n"
    # T if C is ground
    asciiInput += "NOT C T\n"
    # J if (A or B or C) is ground
    asciiInput += "OR T J\n"

    # J if (A or B or C) and D is ground
    asciiInput += "AND D J\n"

    # PART 2
    # jump if D and (H or EI or EF)
    #         D and (H or (E and (I or F)))
    # set T = I, T OR F, T AND E, T OR H
    asciiInput += "NOT I T\n"
    asciiInput += "NOT I T\n"
    asciiInput += "OR F T\n"
    asciiInput += "AND E T\n"
    asciiInput += "OR H T\n"
    # huh....
    asciiInput += "OR E T\n"
    asciiInput += "OR H T\n"
    asciiInput += "AND T J\n"

    # final command
    # asciiInput += "WALK\n"
    asciiInput += "RUN\n"

    intcode_input = asciiToIntcodeInput(asciiInput)
    intcoder = Intcode(data, intcode_input)
    intcoder.run()

    # check intocder output
    if len(intcoder.output) > 0:
        if intcoder.output[-1] > 127:
            print("hull damage:", intcoder.output[-1])
        else:
            print("droid fell")
            print_2d_grid(intcodeOutputToAscii(intcoder.output))
            print()
    else:
        print("ERROR: no intcoder output??")
Beispiel #6
0
def run_tests():
    # opcode, param_modes = parse_instruction(1002)
    # if opcode != 2:
    #     print("wrong opcode")
    # elif param_modes != [0, 1, 0]:
    #     print("wrong param modes")
    # else:
    #     print("tests passed")
    #
    # runcode([3, 0, 4, 0, 99], 444)
    # result = runcode([1002, 4, 3, 4, 33])
    # if result[-1] != 99:
    #     print("failed expected 99")
    #
    po_equal_8 = [3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8]

    Intcode(po_equal_8, 3).run()
    print("expected 0")
    Intcode(po_equal_8, 8).run()
    print("expected 1")
    #
    # po_lt_8 = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]
    #
    # Intcode(po_lt_8, 9).run()
    # print("expected 0")
    #
    # Intcode(po_lt_8, 3).run()
    # print("expected 1")

    im_equal_8 = [3, 3, 1108, -1, 8, 3, 4, 3, 99]

    Intcode(im_equal_8, 3).run()
    print("expected 0")

    Intcode(im_equal_8, 8).run()
    print("expected 1")

    im_lt_8 = [3, 3, 1107, -1, 8, 3, 4, 3, 99]

    # larger = [3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
    #           1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104,
    #           999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]
    #
    # runcode(larger, 7)
    # print("expected 999")
    # runcode(larger, 8)
    # print("expected 1000")
    # runcode(larger, 9)
    # print("expected 1001")
    return
def paint(start_color):
    p = (0, 0)
    d = UP
    grid = {}
    ic = Intcode(input_ints)
    while True:
        color = grid.get(p, 0) if grid else start_color
        ic.add_input(color)
        outputs = list(ic.run_safe())
        if not outputs:
            break
        color, turn = outputs
        grid[p] = color
        d = turn_dir(d, turn)
        p = move_point(p, d)
    return grid
Beispiel #8
0
def part2(origData):
    print(origData)

    goal = 19690720
    guess = 0
    while guess != goal:
        data = deepcopy(origData)
        data[1] = randint(0, 100)
        data[2] = randint(0, 100)

        intcoder = Intcode(data)
        intcoder.run()

        guess = intcoder.state[0]
        print(guess)
    print("answer", data[1] * 100 + data[2])
Beispiel #9
0
def part1(data):
    print(data)

    intcode_input = []
    intcoder = Intcode(data, intcode_input, extra_mem=10000, debug=False)
    intcoder.run()
    output = intcoder.output
    print(output)
    grid = intcodeOutputToAscii(output)
    print_2d_grid(grid)
    intersections = findIntersections(grid)
    print("intersections:", intersections)
    total = 0
    for (x, y) in intersections:
        total += x * y
    print("total", total)
Beispiel #10
0
def part2(data):
    print(data)
    data[0] = 2
    inputs = []
    intcoder = Intcode(data, inputs)
    score = 0
    # possible inputs
    outputs = []
    ballPos = 0
    padPos = 0
    while intcoder.running:
        # check for outputs
        if len(intcoder.output) == 3:
            # print("output",intcoder.output)
            o1, o2, o3 = intcoder.output
            if o3 == 4:
                ballPos = o1
                print("ballPos",ballPos,o2)
                # provide next input
                nextinput = 0
                sign = padPos - ballPos
                if sign > 0:
                    nextinput = -1
                elif sign < 0:
                    nextinput = 1
                inputs.append(nextinput)
                print("nextinput",nextinput)
            if o3 == 3:
                padPos = o1
                print("padPos",padPos,o2)
                # provide next input
                nextinput = 0
                sign = padPos - ballPos
                if sign > 0:
                    nextinput = -1
                elif sign < 0:
                    nextinput = 1
                inputs.append(nextinput)
                print("nextinput",nextinput)
            if o1 == -1 and o2 == 0:
                score = o3
            outputs.append(intcoder.output)
            intcoder.output = []
        intcoder.step()
    print("score",score)
Beispiel #11
0
def part1(data):
    # Get all permutations
    phases = list(permutations([0, 1, 2, 3, 4]))

    largest = -sys.maxsize
    largestphase = []

    # Print the obtained permutations
    for phase in phases:
        ampout = 0
        for ampi in range(0, 5):
            intcoder = Intcode(data.copy(), [phase[ampi], ampout])
            intcoder.run()
            ampout = intcoder.output[0]
        if ampout > largest:
            largest = ampout
            largestphase = phase
    print(largest, "with", largestphase)
class Robot:
    def __init__(self):
        self.ic = Intcode(input_ints)
        self.grid = {}
        self.pos = (0, 0)
        self.moves = []

    def next_pos(self, move):
        dx, dy = VECTORS[move]
        return self.pos[0] + dx, +self.pos[1] + dy

    def move(self, move):
        next_pos = self.next_pos(move)
        self.ic.add_input(move)
        output = list(self.ic.run_safe())[0]
        if output not in VALID_OUTPUT:
            raise Exception(f"invalid output {output}")
        self.grid[next_pos] = output
        if output == WALL:
            return None
        self.pos = next_pos
        return self.pos

    def new_move(self):
        for move in [NORTH, SOUTH, EAST, WEST]:
            next_pos = self.next_pos(move)
            if next_pos in self.grid:
                continue
            pos = self.move(move)
            if pos:
                return move
        return None

    def map_grid(self):
        move = self.new_move()
        if not move:
            raise Exception("first move failed")
        self.moves.append(move)
        while self.moves:
            move = self.new_move()
            if move:
                self.moves.append(move)
            else:
                self.move(INVERSE[self.moves.pop()])
Beispiel #13
0
def run(automatic=False):
    input_ints[0] = 2
    ic = Intcode(input_ints)
    tiles = {}
    s1 = None
    run_step(ic, tiles, draw=True)
    s2 = get_state(tiles)
    while True:
        i = get_auto_input(s1, s2) if automatic else get_key_input()
        ic.add_input(i)
        s1 = s2
        run_step(ic, tiles, draw=True)
        s2 = get_state(tiles)
        if s2[BALL][1] > s2[PADDLE][1]:
            print("GAME OVER!")
            break
        if BLOCK not in tiles.values():
            print("WIN!")
            break
Beispiel #14
0
def part2(data):
    print(data)
    # "Force the vacuum robot to wake up by changing the
    #  value in your ASCII program at address 0 from 1 to 2"
    data[0] = 2

    # found these paths by hand!
    A = ["R", "8", "L", "10", "L", "12", "R", "4"]
    B = ["R", "8", "L", "12", "R", "4", "R", "4"]
    C = ["R", "8", "L", "10", "R", "8"]
    routine = ["A", "B", "A", "C", "A", "B", "C", "B", "C", "B"]

    # convert paths to input
    intcode_input = pathToASCII(routine) + pathToASCII(A) + pathToASCII(
        B) + pathToASCII(C) + [ord("n"), 10]
    print("input", intcode_input)
    # fire it off
    intcoder = Intcode(data, intcode_input, extra_mem=10000, debug=False)
    intcoder.run()
    output = intcoder.output
    print(output[-1])
Beispiel #15
0
def controlRobot(data, startPanelColor=0):
    panels = {(0, 0): startPanelColor}
    loc = (0, 0)
    robotdir = "up"
    robotsteps = 0

    intcode_input = [startPanelColor]
    intcode = Intcode(data, intcode_input, debug=False)

    while intcode.running:
        # check for outputs
        if len(intcode.output) >= 2:
            print("robot outputs:", intcode.output)
            # get output
            paintColor = intcode.output[0]
            newdir = intcode.output[1]

            # paint the current spot
            panels[loc] = paintColor
            print("painted ", loc, " ", paintColor)
            print("panels", panels)

            # move the robot
            print("robot was at:", loc, robotdir)
            loc1, loc2, robotdir = moveRobot(loc, robotdir, newdir)
            loc = (loc1, loc2)
            robotsteps += 1
            if robotsteps > 20000:
                print("ROBOT WENT TOO FAR")
                exit(0)

            # set the color for the new spot
            if panels.get(loc) is not None:
                intcode_input.append(panels[loc])
            else:
                intcode_input.append(0)  # black by default
            print("robot now at:", loc, robotdir)
            intcode.output = []
        intcode.step()
    return panels
def run_phases(phases, memory, feedback=False):
    ics = [Intcode(memory, [p]) for p in phases]
    signals = [0]
    while True:
        for ic in ics:
            ic.inputs = signals + ic.inputs
            next_signals = list(ic.run_safe())
            if not next_signals:
                return signals[0]
            else:
                signals = next_signals
        if not feedback:
            return signals[0]
Beispiel #17
0
def part1(data):
    asciiInput = ""

    # GOAL: if not (A or B or C) and D then jump

    # J if A is ground
    asciiInput += "NOT A J\n"
    # T if B is ground
    asciiInput += "NOT B T\n"
    # J if A or B is ground
    asciiInput += "OR T J\n"

    # T if C is ground
    asciiInput += "NOT C T\n"
    # J if (A or B or C) is ground
    asciiInput += "OR T J\n"

    # J if (A or B or C) and D is ground
    asciiInput += "AND D J\n"

    # final command
    asciiInput += "WALK\n"

    intcode_input = asciiToIntcodeInput(asciiInput)
    intcoder = Intcode(data, intcode_input)
    intcoder.run()

    # check intocder output
    if len(intcoder.output) > 0:
        if intcoder.output[-1] > 127:
            print("hull damage:", intcoder.output[-1])
        else:
            print("droid fell")
            print_2d_grid(intcodeOutputToAscii(intcoder.output))
            print()
    else:
        print("ERROR: no intcoder output??")
Beispiel #18
0
def part1(data):
    print(data)
    num_computers = 50
    packets = []

    # initialize inputs
    inputs = []
    for i in range(num_computers):
        inputs.append([i])

    def intcoder_callback(inpi, address):
        if inpi == 0:
            return address
        # check if there is a packet for it
        for packet in packets:
            if packet[0] == address:
                if packet[3] == 0:
                    packet[3] = 1
                    return packet[1]
                else:
                    val = packet[2]
                    packets.remove(packet)
                    return val
        return -1

    # initialize intcoders
    intcoders = []
    for i in range(num_computers):
        intcoders.append(Intcode(deepcopy(data), intcoder_callback, address=i))

    # packet queue
    while True:
        # check outputs
        for intcoder in intcoders:
            if len(intcoder.output) == 3:
                o = intcoder.output
                o.append(0)
                packets.append(o)
                intcoder.output = []
            intcoder.step()
        # check packets for end condition
        for packet in packets:
            if packet[0] == 255:
                print("answer", packet[2])
                exit(0)
Beispiel #19
0
def part2(data):

    print(data)
    i = j = 10
    points = []

    while True:
        # zig zag down the bottom line
        print("inputs", i, j)
        # in this problem, the intcoder only runs once for each input
        intcoder = Intcode(deepcopy(data), [i, j], debug=False)
        intcoder.run()
        print("output", intcoder.output)
        # down if it's a spot, right if not
        if intcoder.output[0] == 1:
            points.append((i, j))
            # if it's a spot, check the upper right corner
            x = i + 99
            y = j - 99
            if y >= 0:
                print("checking upper corner", x, y)
                intcoder = Intcode(deepcopy(data), [x, y], debug=False)
                intcoder.run()
                if intcoder.output[0] == 1:
                    # we good
                    points.append((x, y))
                    # drawPoints(points)
                    # take the upper left corner
                    # x * 10000 + y
                    points.append((i, y))
                    print("answer:", i * 10000 + y)

                    exit(0)
            # go down
            j += 1
        else:
            # go right
            i += 1
Beispiel #20
0
    #
    # Intcode(po_lt_8, 3).run()
    # print("expected 1")

    im_equal_8 = [3, 3, 1108, -1, 8, 3, 4, 3, 99]

    Intcode(im_equal_8, 3).run()
    print("expected 0")

    Intcode(im_equal_8, 8).run()
    print("expected 1")

    im_lt_8 = [3, 3, 1107, -1, 8, 3, 4, 3, 99]

    # larger = [3, 21, 1008, 21, 8, 20, 1005, 20, 22, 107, 8, 21, 20, 1006, 20, 31,
    #           1106, 0, 36, 98, 0, 0, 1002, 21, 125, 20, 4, 20, 1105, 1, 46, 104,
    #           999, 1105, 1, 46, 1101, 1000, 1, 20, 4, 20, 1105, 1, 46, 98, 99]
    #
    # runcode(larger, 7)
    # print("expected 999")
    # runcode(larger, 8)
    # print("expected 1000")
    # runcode(larger, 9)
    # print("expected 1001")
    return


# run_tests()

Intcode(input_ints, 5).run()
Beispiel #21
0
#!/usr/bin/env python3
import itertools
from os.path import join, dirname, realpath

from lib.intcode import Intcode

input_file = join(dirname(realpath(__file__)), '..', 'inputs', '09.txt')
input_ints = [int(i) for i in open(input_file, 'r').read().split(',')]


def run_tests():
    test1 = [109, 1, 204, -1, 1001, 100, 1, 100, 1008, 100, 16, 101, 1006, 101, 0, 99]
    assert list(Intcode(test1).run()) == test1
    test2 = [1102, 34915192, 34915192, 7, 4, 7, 99, 0]
    assert len(str(list(Intcode(test2).run())[0])) == 16
    test3 = [104, 1125899906842624, 99]
    assert list(Intcode(test3).run())[0] == 1125899906842624


run_tests()

print(list(Intcode(input_ints, inputs=[1]).run()))

print(list(Intcode(input_ints, inputs=[2]).run()))
Beispiel #22
0
def part2(data):
    print(data)
    intcoder = Intcode(data, [2])
    intcoder.run()
    print(intcoder.output)
Beispiel #23
0
def part1(data):
    print(data)
    intcoder = Intcode(data, [1], debug=True)
    intcoder.run()
    print(intcoder.output)
Beispiel #24
0
def part2(data):
    print(data)
    num_computers = 50
    packets = []
    nat = []
    natdelivered = []
    idlecount = 0

    # initialize inputs
    inputs = []
    for i in range(num_computers):
        inputs.append([i])

    def intcoder_callback(inpi, address):
        if inpi == 0:
            return address
        # check if there is a packet for it
        for packet in packets:
            if packet[0] == address:
                if packet[3] == 0:
                    packet[3] = 1
                    return packet[1]
                else:
                    val = packet[2]
                    packets.remove(packet)
                    return val
        return -1

    # initialize intcoders
    intcoders = []
    for i in range(num_computers):
        intcoders.append(Intcode(deepcopy(data), intcoder_callback, address=i))

    # packet queue
    while True:
        # check outputs
        for intcoder in intcoders:
            if len(intcoder.output) == 3:
                o = intcoder.output
                o.append(0)
                if o[0] == 255:
                    nat = deepcopy(o)
                else:
                    packets.append(o)
                intcoder.output = []
            intcoder.step()

        # check for idleness
        if len(packets) == 0:
            idlecount += 1
        if idlecount >= 2000:
            idlecount = 0
            # send last nat packet to address 0
            packet = deepcopy(nat)
            packet[0] = 0
            packets.append(packet)

            # check if we've sent this Y before
            if len(natdelivered) > 0 and packet[2] == natdelivered[-1]:
                print(natdelivered)
                print("answer", packet[2])
                exit(0)
            else:
                natdelivered.append(packet[2])
Beispiel #25
0
def part1(data, input):
    print(data)
    intcoder = Intcode(data, [input], debug=True)
    intcoder.run()
    print(intcoder.output[-1])
Beispiel #26
0
def part2(data, input):
    print(data)
    intcoder = Intcode(data, [input])
    intcoder.run()
    print(intcoder.output[0])
 def __init__(self):
     self.ic = Intcode(input_ints)
     self.grid = {}
     self.pos = (0, 0)
     self.moves = []
Beispiel #28
0
def part1(data):
    print(data)
    random.seed(1)
    steps = 0

    # I randomly explored rooms to draw a map of the rooms
    # then was able to manually write these instructions to
    # visit all rooms with items we might want to take
    to_pressure_plate = ["east","east","west","west", # hull breach
                         "north","east","north","south","west", # gift wrap
                         "north","north","south","south","south", # hull breach
                         "west","west", # hallway
                         "south","east","north","south","west","north", # hallway
                         "north","east","east", # pressure room
                         "inv"]
    ppi = 0
    # manually figured out which items got us the correct weight
    do_not_take = [
        # things that cause you to die if you pick it up
        "photons", "infinite loop", "giant electromagnet", "escape pod", "molten lava",
        # figuring out what weight we need
        "ornament", # is too heavy by itself
        "semiconductor",
        "asterisk",
        "dark matter",
        # "sand",
        # "wreath",
        # "loom",
        # "mutex",
    ]

    intcode_input = [] #asciiToIntcodeInput(movement[0])
    intcoder = Intcode(data, intcode_input)
    while intcoder.running:
        # check output
        if len(intcoder.output) > 0:
            # check output as string
            s = ""
            for o in intcoder.output:
                s += str(chr(o))
            if s[-8:] == "Command?":
                # provide command somehow
                print(s)

                # if we previously took something, other inputs haven't changed,
                if "You take" in s:
                    items = []
                else:
                    # parse output string
                    doors = []
                    items = []

                    doorsi = s.find("Doors here lead:")
                    itemsi = s.find("Items here:")


                    # parse movements
                    if doorsi != -1:
                        doorss = s[doorsi+16:itemsi]
                        ss = doorss.split("- ")
                        doors = ss[1:]
                        doors = [d.split("\n")[0] for d in doors]
                        print("Doors",doors)

                    # parse items
                    if itemsi != -1:
                        itemss = s[itemsi + 11:]
                        ss = itemss.split("- ")
                        items = ss[1:]
                        items = [d.split("\n")[0] for d in items]
                        print("Items",items)


                # somehow decide what to do
                nextInput = ""

                if len(items) > 0 and items[0] not in do_not_take:
                    nextInput = "take " + items[0]
                # go next direction on route
                elif len(doors) > 0:
                    # choose randomly to do initial exploration
                    # random.shuffle(doors)
                    # nextInput = doors[0]
                    nextInput = to_pressure_plate[ppi]
                    ppi += 1
                print("Providing input:",nextInput)
                intcode_input += asciiToIntcodeInput(nextInput)
                intcoder.output = []
        intcoder.step()
        steps += 1

    s = ""
    for o in intcoder.output:
        s += str(chr(o))
    print(s)