예제 #1
0
파일: map.py 프로젝트: thuanpv/Montage
def parse_seed(conf):
    parser = Parser()
    seed_dir = os.path.join(conf.data_dir, 'seed')
    ast_dir = os.path.join(conf.data_dir, 'ast_all')
    make_dir(ast_dir)
    parser.parse(seed_dir, ast_dir)
    return ast_dir
예제 #2
0
    result = []
    for w_s, h_s in angle_sorted:
        # ugly hack to correct the discrepancy
        # between coordinates and the "up" direction
        h_s = -h_s

        sline = takewhile(lambda p: w > p[0] >= 0 and h > p[1] >= 0,
                          scanline(x, y, w_s, h_s))
        scanned = [p for p in sline if p in asteroids]
        if scanned:
            result.append(scanned)

    return result


parser = Parser("Day 10: Monitoring Station - Part 2")
parser.parse()
with parser.input as input:
    data = [line.strip() for line in input]

width = len(data[0])
height = len(data)

flattened = "".join(data)
asteroids = {(i % width, i // width)
             for i, symbol in enumerate(flattened) if symbol == '#'}

x_max, y_max = max(
    asteroids,
    key=lambda p: count_visible_from(p[0], p[1], width, height, asteroids))
예제 #3
0
from utils.parse import Parser
from aoc.intcode import Machine
from itertools import product
from copy import deepcopy


def run_with_params(program, noun, verb):
    program[1] = noun
    program[2] = verb
    computer = Machine(deepcopy(program), lambda: None)
    computer.run()
    return computer.read(0)


parser = Parser("Day 2: 1202 Program Alarm - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

filtered = ((n, v) for n, v in product(range(100), range(100))
            if run_with_params(program, n, v) == 19690720)
noun, verb = next(filtered)

solution = 100 * noun + verb
print(solution)
예제 #4
0
from utils.parse import Parser
from itertools import groupby
from collections import deque
from operator import itemgetter


def is_direct_ore_product(recipes, name):
    _, ings = recipes[name]
    return all(ing == 'ORE' for ing, _ in ings)


parser = Parser("Day 14: Space Stoichiometry - Part 1")
parser.parse()
with parser.input as input:
    split = (l.strip().split('=>') for l in input)
    recipes = {}
    for ingredients, product in split:
        ings = ingredients.strip().split(', ')
        tmp = (el.split() for el in ings)
        ings = [(name, int(amount)) for amount, name in tmp]

        product_amount, product_name = product.split()

        recipes[product_name] = int(product_amount), ings

current_searchspace = deque([('FUEL', 1)])
surpluses = {}
direct_ore_products = []
while current_searchspace:
    name, amount = current_searchspace.popleft()
예제 #5
0
    def dust_amount(self):
        return self.__dust_amount

    def run(self):
        self.__cpu.run()

    def __get_routine(self):
        c = next(self.__it)
        return ord(c)

    def __get_dust(self, value):
        self.__dust_amount = value


# use misc.d17path to obtain the path and then manually divide it into routines
parser = Parser("Day 17: Set and Forget - Part 2")
parser.add_argument("--routine", type=FileType('r'),
                    metavar="ROUTINE", required=True,
                    help="File with movement routine description")
parser.parse()
with parser.input as input, parser.routine as routine:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

    routines = routine.read()

program[0] = 2
robot = VacuumRobot(program, routines)
robot.run()

print(robot.dust_amount)
예제 #6
0
    if d == 'L':
        return x - l, y
    elif d == 'R':
        return x + l, y
    elif d == 'U':
        return x, y + l
    else:
        return x, y - l


def dist(pos):
    x, y = pos
    return abs(x) + abs(y)


parser = Parser("Day 3: Crossed Wires - Part 2")
parser.parse()
with parser.input as input:
    line1 = input.readline()
    wire_a = [(path[:1], int(path[1:])) for path in line1.strip().split(',')]
    line2 = input.readline()
    wire_b = [(path[:1], int(path[1:])) for path in line2.strip().split(',')]

grid_a = Grid()
current_pos = (0, 0)
for d, l in wire_a:
    grid_a.wire(d, current_pos, l)
    current_pos = move_pos(current_pos, d, l)

grid_b = Grid()
current_pos = (0, 0)
예제 #7
0
    def __get_panel_color(self):
        return self.__grid[self.__coordinates]

    def __get_instructions(self, value):
        if self.__color__given:
            turn_side = 1 if value else -1
            self.__dir = self.__dir.turn(turn_side)
            self.__move()
            self.__color__given = False
        else:
            self.__current_color = value
            self.__paint_panel()
            self.__color__given = True


parser = Parser("Day 11: Space Police - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.strip().split(',')]

painter = Painter(deepcopy(program))
painter.paint()

white_panels = {coords for coords, color in painter.grid.items() if color == 1}
max_x = max(x for x, _ in white_panels)
max_y = max(y for _, y in white_panels)
min_x = min(x for x, _ in white_panels)
min_y = min(y for _, y in white_panels)

painted_grid = [[
예제 #8
0
        current_length = path_length

        visited.add(p)
        directions = (d.azimuth for d in Direction)

        x, y = p
        choices = [(x + a_x, y + a_y) for a_x, a_y in directions]
        mapped = map(lambda p: ship_map.get(p, None), choices)
        valid_choices = ((c, m) for c, m in zip(choices, mapped)
                         if c not in visited and m is not None)
        selected_paths = ((path_length + 1, choice)
                          for choice, room in valid_choices
                          if room is not Room.WALL)
        current_searchspace.extend(selected_paths)

    return current_length


parser = Parser("Day 15: Oxygen System - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

controller = Controller(deepcopy(program))
controller.run()

solution = time_to_fill(controller.room_map, controller.oxygen_position)

print(solution)
예제 #9
0
    return list(chained)


def deal_increment(deck, args):
    incr = args.value
    size = len(deck)
    indices = (i % size for i in count(step=incr))
    result = [None for _ in deck]
    for ind, v in zip(indices, deck):
        result[ind] = v

    return result


parser = Parser()
parser.parse()
with parser.input as input:
    lines = (line.strip() for line in input)
    mapped = [parse_instruction(s) for s in lines]

op_mappings = {
    Operation.DEAL_STACK: deal_stack,
    Operation.CUT: cut,
    Operation.DEAL_INCREMENT: deal_increment
}

deck = list(range(10007))
for op, args in mapped:
    deck = op_mappings[op](deck, args)
예제 #10
0
    while True:
        do_time_step(moons)
        positions = (axis_func(m.position) for m in moons)
        velocities = (axis_func(m.velocity) for m in moons)
        state = tuple(zip(positions, velocities))
        if state in states:
            ind = ordered.index(state)
            loop_size = len(states) - ind

            return ind, loop_size

        states.add(state)
        ordered.append(state)


parser = Parser("Day 12: The N-Body Problem - Part 2")
parser.parse()
with parser.input as input:
    stripped = (l.strip('<>\n') for l in input)
    coordinates = (l.split(',') for l in stripped)
    moons = []
    for moon in coordinates:
        values = (coord.strip('xyz= ') for coord in moon)
        position = Vector(*map(int, values))
        moons.append(Moon(position))

_, x_loop = find_loop_in_axis(deepcopy(moons), itemgetter(0))
_, y_loop = find_loop_in_axis(deepcopy(moons), itemgetter(1))
_, z_loop = find_loop_in_axis(deepcopy(moons), itemgetter(2))

tmp_lcm = (x_loop * y_loop) // gcd(x_loop, y_loop)
예제 #11
0
from utils.parse import Parser
from aoc.intcode import Machine

parser = Parser("Day 5: Sunny with a Chance of Asteroids - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

program_input = lambda: 5
program_output = lambda v: None
computer = Machine(program, program_input, program_output)
computer.run()

print(computer.last_output)
예제 #12
0
    def __get_instructions(self, value):
        self.__state_actions[self.__paint_state](value)
        self.__paint_state = self.__paint_state.advance()

    def __read_x(self, x):
        self.__x = x

    def __read_y(self, y):
        self.__y = y

    def __paint_tile(self, value):
        coords = self.__x, self.__y
        self.__grid[coords] = Tile(value)


parser = Parser("Day 13: Care Package - Print Screen")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

arcade = Arcade(deepcopy(program))
arcade.run()

tile_map = {
    Tile.EMPTY: ' ',
    Tile.WALL: '#',
    Tile.BLOCK: 'B',
    Tile.PADDLE: 'P',
    Tile.BALL: '@'
}
예제 #13
0
from utils.parse import Parser
from itertools import zip_longest, tee


def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)


parser = Parser("Day 8: Space Image Format - Part 1")
parser.parse()
with parser.input as input:
    data = [int(c) for c in input.readline().strip()]

w, h = 25, 6
layer_size = w * h
layers = grouper(data, layer_size)
fewest_zeroes = min(layers, key=lambda l: sum(p == 0 for p in l))

ones = sum(p == 1 for p in fewest_zeroes)
twos = sum(p == 2 for p in fewest_zeroes)

print(ones * twos)
예제 #14
0
from utils.parse import Parser
from aoc.intcode import Machine
from copy import deepcopy

parser = Parser("Day 9: Sensor Boost - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

program_input = lambda: 2
computer = Machine(deepcopy(program), program_input)
computer.run()
예제 #15
0
        self.__script = springscript
        self.__it = iter(self.__script)

    @property
    def output(self):
        return self.__cpu.last_output

    def run(self):
        self.__cpu.run()

    def __get_input(self):
        c = next(self.__it)
        return ord(c)


parser = Parser("Day 21: Springdroid Adventure - Part 1")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

script = (
    "NOT C J\n"
    "AND D J\n"
    "NOT A T\n"
    "OR T J\n"
    "WALK\n"
)

droid = SpringDroid(program, script)
droid.run()
예제 #16
0
def calculate_phase(suffix):
    partial_chain = partial_sum_chain(reversed(suffix))
    digits = [abs(v) % 10 for v in partial_chain]
    digits.reverse()
    return digits


def phase_chain(data):
    current = data
    while True:
        current = calculate_phase(current)
        yield current


parser = Parser("Day 16: Flawed Frequency Transmission - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline().strip()
    data = [int(el) for el in line]

# works based on the assumption
# that message offset lies in the second half of the data
message_offset = int(line[:7])

real_data = chain.from_iterable(repeat(data, 10000))
relevant_suffix = list(islice(real_data, message_offset, None))

bound_chain = islice(phase_chain(relevant_suffix), 100)
*_, solution = bound_chain
예제 #17
0
    @property
    def special_msg(self):
        return self.__special_msg

    def run(self):
        while self.__special_msg is None:
            for c in self.__computers:
                c.step()

    def __send_message(self, dest, x, y):
        if dest == 255:
            if self.__special_msg is None:
                self.__special_msg = y
            return

        recipient = self.__computers[dest]
        recipient.queue_message(x, y)


parser = Parser("Day 23: Category Six - Part 1")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

network = Network(program)
network.run()

print(network.special_msg)
예제 #18
0
    opcode = prog_slice[0]
    if not is_valid(opcode):
        return None, []

    op = opcode % 100
    n = get_n_args(op)

    return op, get_args(prog_slice[1:], n, opcode // 100)


def get_arg_symbol(code):
    symbols = {0: "", 1: "#", 2: "@"}
    return symbols[code]


parser = Parser("Intcode prettifier")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

names = {1: "ADD", 2: "MUL", 3: "INP", 4: "OUT", 5: "JNZ", 6: "JEZ", 7: "TLT", 8: "TEQ", 9: "REL", 99: "HLT"}

pos = 0
size = len(program)
while pos < size:
    current_slice = program[pos:]
    op, args = parse_instruction(current_slice)

    name = names.get(op, "??? ({})".format(program[pos]))
    formatted_args = ("{}{}".format(get_arg_symbol(code), value) for code, value in args)
예제 #19
0
from utils.parse import Parser
from itertools import groupby, dropwhile, zip_longest, tee, takewhile
from operator import itemgetter, truth

parser = Parser("Day 6: Universal Orbit Map - Part 2")
parser.parse()
with parser.input as input:
    mappings = (l.strip().split(')') for l in input)
    orbit_map = [(grav, orb) for grav, orb in mappings]

orbit_map = sorted(orbit_map)
grouped = groupby(orbit_map, itemgetter(0))
gravs = {g: [o for _, o in orbs] for g, orbs in grouped}

# depth-first search
current_searchspace = [([], 'COM')]
santa_found = False
me_found = False
while current_searchspace:
    path, g = current_searchspace.pop()
    current_path = path + [g]
    orbiters = ((current_path, orb) for orb in gravs.get(g, []))
    current_searchspace.extend(orbiters)

    if g == 'SAN':
        santa_path = path
        santa_found = True
    elif g == 'YOU':
        me_path = path
        me_found = True
예제 #20
0
    def __get_panel_color(self):
        return self.__grid[self.__coordinates]

    def __get_instructions(self, value):
        if self.__color__given:
            turn_side = 1 if value else -1
            self.__dir = self.__dir.turn(turn_side)
            self.__move()
            self.__color__given = False
        else:
            self.__current_color = value
            self.__paint_panel()
            self.__color__given = True


parser = Parser("Day 11: Space Police - Bonus Art")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.strip().split(',')]

painter = Painter(deepcopy(program))
painter.paint()

white_panels = {coords for coords, color in painter.grid.items() if color == 1}
max_x = max(x for x, _ in white_panels)
max_y = max(y for _, y in white_panels)
min_x = min(x for x, _ in white_panels)
min_y = min(y for _, y in white_panels)

painted_grid = [[
예제 #21
0
        x, y = pos
        adjacent = ((x + az_x, y + az_y) for az_x, az_y in GameOfLife.__dirs)
        n_adjacent_bugs = sum(
            1 for p in adjacent
            if self.__prev.get(p, Entity.EMPTY) is Entity.BUG)

        current_state = self.__prev[pos]

        if current_state is Entity.EMPTY and n_adjacent_bugs in GameOfLife.__infestation_cond:
            return Entity.BUG

        if current_state is Entity.BUG and n_adjacent_bugs != 1:
            return Entity.EMPTY

        return current_state


parser = Parser("Day 24: Planet of Discord - Part 1")
parser.parse()
with parser.input as input:
    coords = ((x, y) for y, x in product(range(5), range(5)))
    stripped = (l.strip() for l in input)
    chained = chain.from_iterable(stripped)
    mappings = {'.': Entity.EMPTY, '#': Entity.BUG}
    initial_state = {pos: mappings[v] for pos, v in zip(coords, chained)}

game = GameOfLife(initial_state)
game.run()

print(game.current_biodiversity)
예제 #22
0
        self.__phase_given = True
        return self.__phase


def run_feedback_loop(phases, prog):
    links = [Link(p, 0) for p in phases]
    linkage = pairwise(cycle(links))
    comps = [
        Machine(deepcopy(prog), i, o) for i, o in islice(linkage, len(links))
    ]
    for c in comps:
        c.break_on_output = True
    while not all(c.halted for c in comps):
        for c in comps:
            c.start_or_resume()

    return comps[-1].last_output


parser = Parser("Day 7: Amplification Circuit - Part 2")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

max_output = max(
    run_feedback_loop(t, program) for t in permutations(range(5, 10)))

print(max_output)
예제 #23
0
        self.__next_position = None

    @property
    def pulled(self):
        return self.__pulled

    def run(self):
        for pos in product(range(self.__grid_size), range(self.__grid_size)):
            self.__next_position = iter(pos)
            self.__drone = Machine(deepcopy(self.__program_copy),
                                   self.__get_position, self.__get_output)
            self.__drone.run()

    def __get_position(self):
        return next(self.__next_position)

    def __get_output(self, value):
        self.__pulled += value


parser = Parser("Day 19: Tractor Beam - Part 1")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

scanner = Scanner(deepcopy(program), 50)
scanner.run()

print(scanner.pulled)
예제 #24
0
        self.__cpu.run()

    def __get_pixel(self, ascii):
        c = chr(ascii)
        x, y = self.__position

        mapping = self.__char_mapping.get(c, None)
        if mapping is None:
            self.__position = 0, y + 1
            return

        self.__image[self.__position] = mapping
        self.__position = x + 1, y


parser = Parser("Day 17: Set and Forget - Part 1")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

camera = Camera(deepcopy(program))
camera.run()

image = camera.image

min_x = min(x for x, _ in image.keys())
min_y = min(y for _, y in image.keys())
max_x = max(x for x, _ in image.keys())
max_y = max(y for _, y in image.keys())
예제 #25
0
    a, b = tee(iterable)
    next(b, None)
    return zip(a, b)


def is_valid(password):
    group_len = 1
    is_adjacent_pair_same = False
    for first, second in pairwise(password):
        if first > second:
            return False

        if first == second:
            group_len += 1
        else:
            if group_len == 2:
                is_adjacent_pair_same = True
            group_len = 1

    return group_len == 2 or is_adjacent_pair_same


parser = Parser("Day 4: Secure Container - Part 2")
parser.parse()
with parser.input as input:
    a, b = map(int, input.readline().split('-'))

n_valid = sum(is_valid(str(n)) for n in range(a, b + 1))

print(n_valid)
예제 #26
0
    def run(self):
        self.__cpu.run()

    def __get_instructions(self, value):
        self.__state_actions[self.__paint_state](value)
        self.__paint_state = self.__paint_state.advance()

    def __read_x(self, x):
        self.__x = x

    def __read_y(self, y):
        self.__y = y

    def __paint_tile(self, value):
        coords = self.__x, self.__y
        self.__grid[coords] = Tile(value)


parser = Parser("Day 13: Care Package - Part 1")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

arcade = Arcade(deepcopy(program))
arcade.run()

n_blocks = sum(1 for tile in arcade.grid.values() if tile is Tile.BLOCK)

print(n_blocks)
예제 #27
0
 def parse(self):
     make_dir(self._ast_dir)
     parser = Parser()
     parser.parse(self._seed_dir, self._ast_dir)
예제 #28
0
from utils.parse import Parser


def fuel_req(mass):
    return mass // 3 - 2


parser = Parser("Day 1: The Tyranny of the Rocket Equation - Part 1")
parser.parse()
with parser.input as input:
    modules = [int(val) for val in input]

total_fuel = sum(fuel_req(m) for m in modules)
print(total_fuel)
예제 #29
0
        c = next(self.__input_it, None)

        if c is None:
            input_line = input('#> ')
            self.__input = [input_line, '\n']
            self.__input_it = chain.from_iterable(self.__input)
            c = next(self.__input_it)

        return ord(c)

    def __get_output(self, ascii):
        c = chr(ascii)
        self.__output.append(c)

    def __flush_output(self):
        outprint = "".join(self.__output)
        print(outprint)
        self.__output.clear()


# This part is interactive, navigate Santa's ship
# and get through the Pressure-Sensitive Floor to win!
parser = Parser("Day 25: Cryostasis - Part 1")
parser.parse()
with parser.input as inp:
    line = inp.readline()
    program = [int(el) for el in line.split(',')]

droid = Droid(program)
droid.run()
예제 #30
0
        c = chr(ascii)
        x, y = self.__position

        mapping = self.__char_mapping.get(c, None)
        if mapping is None:
            self.__position = 0, y + 1
            return

        if mapping.is_robot:
            self.__vacuum_robot = self.__position, self.__dir_mapping[mapping]

        self.__image[self.__position] = mapping
        self.__position = x + 1, y


parser = Parser("Day 17: Set and Forget - Path Finder")
parser.parse()
with parser.input as input:
    line = input.readline()
    program = [int(el) for el in line.split(',')]

camera = Camera(deepcopy(program))
camera.run()

image = camera.image

min_x = min(x for x, _ in image.keys())
min_y = min(y for _, y in image.keys())
max_x = max(x for x, _ in image.keys())
max_y = max(y for _, y in image.keys())