Ejemplo n.º 1
0
Archivo: day11.py Proyecto: fis/aoc-go
def robot(prog, white=set()):
    painted = set()
    rpos, rdir = [0, 0], [0, -1]
    cycle = ['paint']  # or 'turn'

    def robot_in():
        return 1 if tuple(rpos) in white else 0

    def robot_out(n):
        if cycle[0] == 'paint':
            cycle[0] = 'turn'
            p = tuple(rpos)
            painted.add(p)
            if n == 0:   white.discard(p)
            elif n == 1: white.add(p)
            else: raise RuntimeError(f'bad paint: {n}')
        else:
            cycle[0] = 'paint'
            dx, dy = rdir[0], rdir[1]
            if n == 0:   dx, dy = dy, -dx
            elif n == 1: dx, dy = -dy, dx
            else: raise RuntimeError(f'bad turn: {n}')
            rpos[0] += dx
            rpos[1] += dy
            rdir[0] = dx
            rdir[1] = dy

    intcode.run(prog, stdin=robot_in, stdout=robot_out)

    return white, painted
Ejemplo n.º 2
0
Archivo: day13.py Proyecto: fis/aoc-go
def demo():
    out = ['x', 0, 0]
    pad_x, ball_x = [0], [0]
    score = [0]

    def demo_in():
        if ball_x[0] < pad_x[0]: return -1
        if ball_x[0] > pad_x[0]: return 1
        return 0

    def demo_out(n):
        if out[0] == 'x':
            out[0] = 'y'
            out[1] = n
        elif out[0] == 'y':
            out[0] = 't'
            out[2] = n
        else:
            out[0] = 'x'
            x, y = out[1:3]
            if x == -1 and y == 0:
                score[0] = n
            else:
                if n == 3: pad_x[0] = x
                if n == 4: ball_x[0] = x

    intcode.run(prog, stdin=demo_in, stdout=demo_out)
    return score[0]
Ejemplo n.º 3
0
def part2():
    program = intcode.readProgram("input")
    pcopy = program.copy()

    output = []
    intcode.run(program, [], output)
    draw(output)
    coords = toCoords(output)
    pos = findVacuumRobot(coords)
    mm = movement(coords, pos, coords[pos])
    mm = list(map(str, mm))
    # print(mm)
    pred = lambda sl: len(",".join(sl)) <= 20
    (names, mappings) = split(mm, pred, 0, [])

    # print(names)
    # print(mappings)

    program = pcopy
    program[0] = 2 # activate

    inputs = [",".join(names) + "\n"]
    for k in sorted(mappings.keys(), key=ord):
        inputs.append(",".join(mappings[k]) + "\n")
    inputs.append("n\n")

    def toAscii(inp): return list(map(ord, splitStr(inp)))
    inputs = flatten(list(map(toAscii, inputs)))

    print(inputs)
    output = []
    state = intcode.run(program, inputs, output)
    print("done? %s" % (state[0],))
    print(output)
Ejemplo n.º 4
0
Archivo: day13.py Proyecto: fis/aoc-go
def game(scr):
    curses.curs_set(0)
    out = ['x', 0, 0]

    def game_in():
        ch = scr.getch()
        if ch == curses.KEY_LEFT: return -1
        if ch == curses.KEY_RIGHT: return 1
        return 0

    def game_out(n):
        if out[0] == 'x':
            out[0] = 'y'
            out[1] = n
        elif out[0] == 'y':
            out[0] = 't'
            out[2] = n
        else:
            out[0] = 'x'
            x, y = out[1:3]
            if x == -1 and y == 0:
                scr.addstr(0, 0, str(n))
            else:
                scr.addch(y+1, x, tiles[n])
            scr.refresh()

    intcode.run(prog, stdin=game_in, stdout=game_out)
Ejemplo n.º 5
0
def scan(program, mx, my):
    for x in range(0, mx):
        for y in range(0, my):
            output = []
            inp = [x, y]
            intcode.run(program.copy(), inp, output)
            yield (x, y, output[0])
Ejemplo n.º 6
0
def calc_phase_setting(initial_memory: List[int],
                       sequence: Iterable[int]) -> int:
    phase_setting = 0
    programs: List[Program] = []
    halted = False

    while not halted:
        for i, program_input in enumerate(sequence):
            if len(programs) <= i:
                programs.append(Program(initial_memory))

                # Run with program_input only first time
                _, outputs = run(programs[i],
                                 inputs=[program_input, phase_setting])
            else:
                # Already added -> has run at least once already
                _, outputs = run(programs[i], inputs=[phase_setting])

            assert len(outputs) > 0
            phase_setting = outputs[-1]

            halted = programs[i].memory[programs[i].memory_ptr] == 99
            if halted:
                programs[i].memory_ptr = 0

    return phase_setting
Ejemplo n.º 7
0
Archivo: day21.py Proyecto: fis/aoc-go
def run(sprog):
    out = []
    intcode.run(prog,
                stdin=[ord(c) for c in '\n'.join(sprog) + '\n'],
                stdout=out)
    print(''.join(chr(c) for c in out if c < 256))
    return out[-1]
Ejemplo n.º 8
0
def get_final_output(ops, input):
    latestOutput = None
    state = run(ProgramState(ops), input)
    while not state.done:
        latestOutput = state.output
        # print (latestOutput)
        state = run(state, [])
    return latestOutput
Ejemplo n.º 9
0
def main():
    global grid
    # Prepare intcode computer
    intcode.init('inputs/painting.txt')
    intcode.run(i=instr_in, o=instr_out)
    # How many panels painted at least once?
    # print(len(grid))
    paintID()
Ejemplo n.º 10
0
def boost(ops, inp):
    outputs = []
    state = run(ProgramState(ops), [inp])
    while not state.done:
        print (state.output)
        outputs.append(state.output)
        state = run(state, [])
    print (state.memory)
    return outputs
Ejemplo n.º 11
0
def day2(input_path):
    with open(input_path) as f:
        rom = np.ascontiguousarray(list(map(int, f.read().split(","))))

    ram = rom.copy()
    ram[1] = 12
    ram[2] = 2
    intcode.run(ram, 0)
    assert ram[0] == 5290681
    assert search(rom) == 5741
Ejemplo n.º 12
0
def search(rom):
    for noun in range(100):
        for verb in range(100):
            ram = rom.copy()
            ram[1] = noun
            ram[2] = verb
            intcode.run(ram, 0)
            if ram[0] == 19690720:
                return noun * 100 + verb

    raise RuntimeError("Not found")
Ejemplo n.º 13
0
def execute(code):
    program = [[ord(c) for c in line + "\n"] for line in code.split("\n")]
    i = []
    m = list(data)
    o = []
    # Test run once
    p, r = run(i, m, o)
    for i in program:
        p, r = run(i, m, o, p, r)
    #print(''.join(chr(x) for x in o if x < 256))
    return o[-1]
Ejemplo n.º 14
0
def test_run_example():
    mem, ip, inputs, outputs = run([3, 0, 4, 0, 99], inputs=[42])
    assert mem == [42, 0, 4, 0, 99]
    assert ip == 4
    assert not inputs
    assert outputs == [42]

    memory = [1002, 4, 3, 4, 33]
    assert run(memory) == ([1002, 4, 3, 4, 99], 4, [], [])

    memory = [1101, 100, -1, 4, 0]
    assert run(memory) == ([1101, 100, -1, 4, 99], 4, [], [])
Ejemplo n.º 15
0
def part1():
    program = intcode.readProgram("input")
    output = []
    intcode.run(program, [], output)
    coords = toCoords(output)
    intersectionPoints = filter(lambda p:isIntersection(coords, p), coords.keys())

    #width = output.index(10)
    #for p in intersectionPoints:
    #    (x, y) = p
    #    idx = (width+1)*y + x
    #    output[idx] = ord("O")
    #draw(output)

    return sum(map(lambda p: p[0]*p[1], intersectionPoints))
Ejemplo n.º 16
0
def build_graph(program):
    dists = {}
    graph = defaultdict(list)
    inps = []
    prog = intcode.run(program, inps)

    oxpos = None

    def move(cmd):
        inps.append(cmd)
        return next(prog)

    def dfs(pos, dist):
        nonlocal oxpos
        dists[pos] = dist
        for cmd, delta in d.items():
            npos = (pos[0] + delta[0], pos[1] + delta[1])
            curdist = dists.get(npos, math.inf)
            if dist >= curdist:
                continue
            status = move(cmd)
            if status == 2:
                oxpos = npos
            if status == 1 or status == 2:
                graph[pos].append(npos)
                graph[npos].append(pos)
                dfs(npos, dist + 1)
                move(reverse[cmd])

    dfs((0, 0), 0)

    return graph, oxpos, dists[oxpos]
Ejemplo n.º 17
0
def run_prog(prog, inp=[]):
    outs = []
    for mem, out, pc, running in ic.run(prog, iter(inp)):
        if not running:
            return outs
        if out is not None:
            outs.append(out)
Ejemplo n.º 18
0
def part2(program, seq):
    program[0] = 2
    seqs = simplify(seq)
    distinct = list(set(seqs))
    main = ','.join(chr(ord('A') + distinct.index(x)) for x in seqs)
    lines = [main] + distinct + ['n\n']
    return list(intcode.run(program, '\n'.join(lines)))[-1]
Ejemplo n.º 19
0
def a():
    out = defaultdict(int)
    for x, y, tile in u.chunks(intcode.run(data, []), 3):
        out[(x, y)] = tile
    # print_tiles(out)
    blocks = len([v for v in out.values() if v == 2])
    return blocks
Ejemplo n.º 20
0
def test_jumps():
    memory = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]
    _, _, _, outputs = run(memory, inputs=[0])
    assert outputs == [0]

    memory = [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]
    _, _, _, outputs = run(memory, inputs=[0])
    assert outputs == [0]

    memory = [3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9]
    _, _, _, outputs = run(memory, inputs=[123])
    assert outputs == [1]

    memory = [3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1]
    _, _, _, outputs = run(memory, inputs=[123])
    assert outputs == [1]
Ejemplo n.º 21
0
def first():
    state = read_state()
    state[1] = 12
    state[2] = 2

    result = intcode.run(state)
    print(result)
Ejemplo n.º 22
0
 def __init__(self, program):
     self.field, self.pos, self.dir = set(), None, None
     for y, line in enumerate(''.join(map(chr,
                                          intcode.run(program,
                                                      ()))).split('\n')):
         for x, char in enumerate(line):
             if char == '#':
                 self.field.add((x, y))
             elif char == '<':
                 self.pos = x, y
                 self.dir = -1, 0
             elif char == '>':
                 self.pos = x, y
                 self.dir = 1, 0
             elif char == '^':
                 self.pos = x, y
                 self.dir = 0, -1
             elif char == 'v':
                 self.pos = x, y
                 self.dir = 0, 1
     self.crossings = {
         (x, y)
         for x, y in self.field
         if sum(((x - 1, y) in self.field, (x, y - 1) in self.field,
                 (x, y + 1) in self.field, (x + 1, y) in self.field)) > 2
     }
Ejemplo n.º 23
0
def test_opcode7():
    memory = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]
    _, _, _, outputs = run(memory, inputs=[8])
    assert outputs == [0]

    memory = [3, 3, 1107, -1, 8, 3, 4, 3, 99]
    _, _, _, outputs = run(memory, inputs=[8])
    assert outputs == [0]

    memory = [3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8]
    _, _, _, outputs = run(memory, inputs=[4])
    assert outputs == [1]

    memory = [3, 3, 1107, -1, 8, 3, 4, 3, 99]
    _, _, _, outputs = run(memory, inputs=[4])
    assert outputs == [1]
Ejemplo n.º 24
0
def main():
  inputHandle = loadFile("02/input.txt")
  opList = fileToList(inputHandle, ",")

  for noun, verb in product(range(0, 100), range(0, 100)):
    if run(noun, verb, opList) == 19690720:
      print( (100 * noun) + verb)
      break
Ejemplo n.º 25
0
 def runOnce(self):
     inputs = self.queue
     if len(inputs) == 0:
         inputs = [-1]
     self.queue = []
     output = []
     self.state = intcode.run(self.program, inputs, output, self.state)
     self.network.send(output)
Ejemplo n.º 26
0
def run_tests():
    test_i = 0
    for tape, input, expected in tests:
        result = intcode.run(tape.copy(), input.copy())
        if result[1] != expected:
            print(test_i, 'failed')
            print('got', result[1])
            print('instead of', expected)
        test_i += 1
Ejemplo n.º 27
0
Archivo: 2.py Proyecto: rpearl/advent
def evaluate(noun, verb):
    mem = defaultdict(int, enumerate([int(v) for v in data.split(",")]))
    mem[1] = noun
    mem[2] = verb

    for _ in intcode.run(mem, []):
        pass

    return mem[0]
Ejemplo n.º 28
0
def part2(lines):
    program = [int(s.strip()) for s in lines[0].split(',')]
    scaffold = Scaffold(program[:])
    input = '\n'.join(
        next(result for path in scaffold.paths() for result in compress(path)))
    program[0] = 2
    for x in intcode.run(program, [ord(c) for c in f'{input}\nn\n']):
        if x > 255:
            return x
Ejemplo n.º 29
0
def scan(x, y):
    if x < 0 or y < 0:
        return 0
    i = [x, y]
    m = list(data)
    o = []
    # Test run once
    p, r = run(i, m, o)
    return o[0]
Ejemplo n.º 30
0
def part2(program: list):
    inputs = itertools.product(range(100), range(100))
    for n, v in inputs:
        memory = program.copy()
        memory[1] = n
        memory[2] = v
        memory, _, _, _ = run(memory)
        if memory[0] == 19690720:
            break
    return n * 100 + v