Esempio n. 1
0
 def __init__(self, code, map_sz):
   self.cpu = Intcode(code, False, True)
   # self.area_map = [["?" for _ in range(map_sz)] for _ in range(map_sz)]
   self.pos = [map_sz // 2, map_sz // 2]
   with open("day15/map.txt") as fd:
     self.area_map = [[c for c in line] for line in fd.read().splitlines()]
     fd.close()
Esempio n. 2
0
def part1():
  comp = Intcode(code, halt_on_output=True)
  r = comp.exec()
  comp_out = []
  while comp.halt_fg:
    comp_out.append(r)
    r = comp.resume()

  out = np.array(comp_out)
  out = out.reshape(len(out) // 3, 3)

  unique, counts = np.unique(out[:, 2], return_counts=True)
  print(dict(zip(unique, counts)))
Esempio n. 3
0
def part2():
    amplifiers = [Intcode(code, halt_on_output=True) for _ in range(5)]

    amp_out = np.array([(amplifier_feedback(amplifiers, phase_seq), phase_seq)
                        for phase_seq in permutations(range(5, 10), 5)])

    max_ndx = np.argmax(amp_out[:, 0])
    print(amp_out[max_ndx])
Esempio n. 4
0
def part1():
    amplifiers = [Intcode(code) for _ in range(5)]

    amp_out = np.array([(amplifier_sequencer(amplifiers, phase_seq), phase_seq)
                        for phase_seq in permutations(range(0, 5), 5)])

    max_ndx = np.argmax(amp_out[:, 0])
    print(amp_out[max_ndx])
Esempio n. 5
0
    def __init__(self, code, game_mode=1):
        code[0] = game_mode
        self.comp = Intcode(code, halt_on_output=True)
        out_raw = [self.comp.exec()]
        for _ in range(_board_sz - 1):
            out_raw.append(self.comp.resume())

        out = np.array(out_raw)
        out = out.reshape(len(out) // 3, 3)
        x_mx = np.argmax(out[:, 0]) + 1
        y_mx = np.argmax(out[:, 1]) + 1
        self.board = [[0 for _ in range(x_mx)] for _ in range(y_mx)]

        for x, y, tile_id in out:
            self.board[y][x] = tile_id

        if game_mode == 2:
            _, _, self.score = self.step()
        else:
            self.score = 0
Esempio n. 6
0
 def __init__(self, code, mode=1):
     self.cpu = Intcode(code, halt_on_output=True)
     self.cpu._code[0] = mode
     self.update_feed()
Esempio n. 7
0
class Droid:
    def __init__(self, code, mode=1):
        self.cpu = Intcode(code, halt_on_output=True)
        self.cpu._code[0] = mode
        self.update_feed()

    def update_feed(self):
        out = [str(chr(self.cpu.exec()))]
        for _ in range(2340):
            out.append(str(chr(self.cpu.resume())))

        out_str = "".join(out)
        self.area_map = [[c for c in line] for line in out_str.splitlines()]
        print(self)

    def read_line(self):
        ret = -1
        rtcd = []
        while ret != 10:
            ret = self.cpu.resume()
            rtcd.append(ret)

        return "".join([chr(c) for c in rtcd[:-1]])

    def input_read_line(self, *cpu_in):
        ret = [self.cpu.resume(*cpu_in)]
        while ret[-1] != 10:
            ret.append(self.cpu.resume())

        return "".join([chr(c) for c in ret[:-1]])

    def _check_alignment(self, i, j):
        return (self.area_map[j - 1][i] == "#"
                and self.area_map[j][i - 1] == "#"
                and self.area_map[j][i + 1] == "#"
                and self.area_map[j + 1][i] == "#")

    def get_alignment(self):
        ret = 0
        for j, row in enumerate(self.area_map[1:-1]):
            for i, v in enumerate(row[1:-1]):
                if v == "#" and self._check_alignment(j + 1, i + 1):
                    ret += (i + 1) * (j + 1)

        return ret

    def program(self, main, f_a, f_b, f_c, display_camera=True):

        print(self.read_line())
        main_int = [ord(c) for c in main]
        f_a_int = [ord(c) for c in f_a]
        f_b_int = [ord(c) for c in f_b]
        f_c_int = [ord(c) for c in f_c]

        print(self.input_read_line(*main_int, ord("\n")))
        print(self.input_read_line(*f_a_int, ord("\n")))
        print(self.input_read_line(*f_b_int, ord("\n")))
        print(self.input_read_line(*f_c_int, ord("\n")))
        print(
            self.input_read_line(
                ord('y') if display_camera else ord('n'), ord("\n")))

        if display_camera:
            while self.cpu.halt_fg:
                self.update_feed()
                print(self)
        else:
            for _ in range(40):
                print(self.read_line())
            print(self.cpu.resume())

    def __repr__(self):
        return "\n".join(["".join(c for c in line) for line in self.area_map])
Esempio n. 8
0
from cpu import Intcode

fp = "day11/code.txt"
with open(fp) as fd:
    text = fd.read()
    bot = Intcode([int(d) for d in text.split(",")], halt_on_output=True)
sz = 200


class Navigation:
    x = int(sz / 2)
    y = int(sz / 2)
    direction = "UP"

    def advance(self):
        if self.direction == "UP":
            self.y -= 1
        elif self.direction == "DOWN":
            self.y += 1
        elif self.direction == "RIGHT":
            self.x += 1
        elif self.direction == "LEFT":
            self.x -= 1

    def rotate(self, turn_right_fg):
        if turn_right_fg:
            if self.direction == "UP":
                self.direction = "RIGHT"
            elif self.direction == "RIGHT":
                self.direction = "DOWN"
            elif self.direction == "DOWN":
Esempio n. 9
0
from cpu import Intcode

# fp = "day9/ex1.txt"
fp = "day9/in.txt"
with open(fp) as fd:
    code = [int(x) for x in fd.read().split(",")]

comp = Intcode(code, True)


def part1(comp):
    print(comp.exec(1))


def part2(comp):
    print(comp.exec(2))


# part1(comp)
part2(comp)
Esempio n. 10
0
class Droid:

  def __init__(self, code, map_sz):
    self.cpu = Intcode(code, False, True)
    # self.area_map = [["?" for _ in range(map_sz)] for _ in range(map_sz)]
    self.pos = [map_sz // 2, map_sz // 2]
    with open("day15/map.txt") as fd:
      self.area_map = [[c for c in line] for line in fd.read().splitlines()]
      fd.close()

  def explore_man(self):
    dirs = {"w": 1, "a": 3, "s": 2, "d": 4}
    direction = 1
    rtcd = self.cpu.exec(1)
    while rtcd != 2:
      new_pos = self.mark(direction, "#" if rtcd == 0 else " ")
      if rtcd != 0:
        self.pos = new_pos

      print(self)
      print("Direction (w,a,s,d): ")
      # direction = dirs.get(input("Direction (w, a, s, d): "), 1)
      # a = msvcrt.getch().decode("utf-8")
      key_in = msvcrt.getch().decode("utf-8")
      if key_in == "q":
        with open("day15/map.txt", "w+") as fd:
          fd.write(self.__repr__())
        break

      direction = dirs.get(key_in, 1)

      rtcd = self.cpu.resume(direction)

  def explore_ai(self):
    routes = []
    routes.append([1])
    rtcd = self.cpu.exec(1)
    while rtcd != 2:
      new_pos = self.mark(, "#" if rtcd == 0 else " ")
      if rtcd != 0:
        self.pos = new_pos
      direction = random.randint(1, 4)

      rtcd = self.cpu.resume(direction)
      print("Area")
      print(self)

  def mark(self, direction, char):
    new_pos = self.pos.copy()
    if direction == 1:
      new_pos[1] -= 1
    elif direction == 2:
      new_pos[1] += 1
    elif direction == 3:
      new_pos[0] -= 1
    elif direction == 4:
      new_pos[0] += 1
    else:
      raise RuntimeError(f"Unknown direction {direction}")

    self.area_map[new_pos[1]][new_pos[0]] = char
    return new_pos

  def __repr__(self):
    self.area_map[self.pos[1]][self.pos[0]] = "D"
    ret = "\n".join(["".join([c for c in line]) for line in self.area_map])
    self.area_map[self.pos[1]][self.pos[0]] = " "
    return ret
Esempio n. 11
0
class Game:
    def __init__(self, code, game_mode=1):
        code[0] = game_mode
        self.comp = Intcode(code, halt_on_output=True)
        out_raw = [self.comp.exec()]
        for _ in range(_board_sz - 1):
            out_raw.append(self.comp.resume())

        out = np.array(out_raw)
        out = out.reshape(len(out) // 3, 3)
        x_mx = np.argmax(out[:, 0]) + 1
        y_mx = np.argmax(out[:, 1]) + 1
        self.board = [[0 for _ in range(x_mx)] for _ in range(y_mx)]

        for x, y, tile_id in out:
            self.board[y][x] = tile_id

        if game_mode == 2:
            _, _, self.score = self.step()
        else:
            self.score = 0

    def step(self):
        return self.comp.resume(), self.comp.resume(), self.comp.resume()

    def step_with_input(self, joy_in):
        return self.comp.resume(joy_in), self.comp.resume(), self.comp.resume()

    def update(self, joy_in):
        x, y, arg = self.step_with_input(joy_in)
        self.board[y][x] = arg

        if joy_in != 0:
            x, y, arg = self.step()
            self.board[y][x] = arg

            x, y, arg = self.step()
            self.board[y][x] = arg

        x, y, arg = self.step()
        while x == -1 and y == 0:
            # Update sore
            self.score = arg

            # Delete the block
            x, y, arg = self.step()
            if not self.comp.halt_fg:
                return
            self.board[y][x] = arg

            # Update ball
            x, y, arg = self.step()

        self.board[y][x] = arg

    def get_ball_loc(self):
        for j, row in enumerate(self.board):
            if 4 in row:
                return row.index(4), j

        raise Exception("No ball found")

    def get_paddle_loc(self):
        return self.board[21].index(3)

    def __repr__(self):
        return "\n".join([
            "".join([_id_to_tile[i] for i in row]) for row in self.board[:23]
        ]) + f"\nScore: {self.score}"