Exemple #1
0
def part2():
    for noun in range(100):
        for verb in range(100):
            data = get_input(2)
            # before running the program, replace position 1 with the value 12 and replace position 2 with the value 2
            data[1] = noun
            data[2] = verb
            for instructions in map(
                    lambda digits: InstructionSet(*digits),
                (x for x in (data[i:i + 4] for i in range(0, len(data), 4)))):
                if instructions.opcode == 1:
                    data[instructions.dest_pos] = data[
                        instructions.pos1] + data[instructions.pos2]
                elif instructions.opcode == 2:
                    data[instructions.dest_pos] = data[
                        instructions.pos1] * data[instructions.pos2]
                elif instructions.opcode == 99:
                    # print("Process complete.\nFinal state: {}".format(data))
                    break
                else:
                    print("Execution error! Unknown opcode: {}".format(
                        instructions.opcode))

            if data[0] == 19690720:
                return 100 * noun + verb
Exemple #2
0
def part2():
    wires, d = [], {}
    wires.extend(list(map(lambda wire: wire.split(','), get_input(3))))
    for i, wire in enumerate(wires):
        x = y = steps = 0
        for instruction in wire:
            direction, distance = instruction[0], int(instruction[1:])
            if direction in ('L', 'R'):
                delta = (1 if direction == 'R' else -1, 0)
            else:
                delta = (0, 1 if direction == 'U' else -1)
            for _ in range(distance):
                steps += 1
                x += delta[0]
                y += delta[1]
                if (x, y) not in d:
                    d[(x, y)] = {'seen': set(), 'steps': {i: steps}}
                if i not in d[(x, y)]['steps']:
                    d[(x, y)]['steps'][i] = steps
                d[(x, y)]['seen'].add(i)

    intersections = list(
        filter(lambda coord: len(coord[1]['seen']) > 1, d.items()))
    return min(
        map(lambda coord: sum(coord[1]['steps'].values()), intersections))
def test_get_input():
    text_input = TEST_INPUT[:3] + (None, ) + TEST_INPUT[3:]
    get_row = Mock(side_effect=text_input)
    print_func = Mock()
    result = get_input(get_row_func=get_row, print_func=print_func)
    assert result == TEST_INPUT
    assert get_row.call_count == 6
    assert print_func.call_count == 1
Exemple #4
0
def part2():
    data = get_input(1)
    total_fuel_needed = 0
    for mass in data:
        incremental_fuel = int(int(mass) / 3) - 2
        while (incremental_fuel > 0):
            total_fuel_needed += incremental_fuel
            incremental_fuel = int(incremental_fuel / 3) - 2
    print(total_fuel_needed)
Exemple #5
0
def main():
    board = Board()

    import atexit
    original_terminal_state = lib.set_terminal_mode()
    atexit.register(lib.restore_terminal, original_terminal_state)

    # game loop
    while board.alive:
        board.draw()
        delay = board.stats.delay

        # if nothing's falling, wait a bit then spawn a piece
        if board.kind is None:
            lib.get_input(lib.now() + delay)
            if board.clear_lines():
                lib.get_input(lib.now() + delay)
            board.spawn()
            continue

        # let the player shift and rotate freely before the next down-step
        deadline = lib.now() + delay
        key = None
        while key != 'down':
            key = lib.get_input(deadline)
            if key == 'left':
                board.shift(-1)
            elif key == 'right':
                board.shift(1)
            elif key == 'up':
                board.rotate()
            elif key == 'space':
                board.hard_drop()
                break
            else:
                break

        # down-step
        if board.kind is not None:
            board.descend()

    board.draw()
    print()
    print('GAME OVER!')
Exemple #6
0
def part1():
    input = (int(x) for x in get_input(8)[0])
    layer, layers = None, []
    for i, num in enumerate(input):
        if i % 150 == 0:
            if layer:
                layers.append(layer)
            layer = []
        layer.append(num)
    chosen_layer = sorted(layers, key=lambda x: x.count(0))[0]
    return chosen_layer.count(1) * chosen_layer.count(2)
Exemple #7
0
def prep_data():
    data = []
    data.extend(list(map(lambda wire: wire.split(','), get_input(3))))
    h_lines, v_lines = [], []
    x, y = 0, 0
    for line in chain(data[0], data[1]):
        print(line)
        (x2, y2), horizontal = parse_instruction(line)
        if horizontal:
            h_lines.append(Line(x, x2, y, y2))
        else:
            v_lines.append(Line(x, x2, y, y2))
        x = x2
        y = y2
    return h_lines, v_lines
Exemple #8
0
def part1():

    d = {}
    for phase_group in permutations(range(5)):
        out = 0
        for phase_setting in phase_group:
            _input = [int(x) for x in get_input(7, log=False)[0].split(',')]
            i = Intcode(_input=_input,
                        use_phase_settings=True,
                        phase_setting=phase_setting,
                        input_signal=out)
            i.run()
            out = i.diagnostic_codes[0]
        d[phase_group] = out
    print(next(filter(lambda item: item[1] == max(d.values()), d.items())))
Exemple #9
0
 def __init__(self,
              day=2,
              _input=None,
              use_phase_settings=False,
              phase_setting=0,
              input_signal=0,
              print_output=False):
     self.instruction_pointer = 0
     self.input = get_input(day) if not _input else _input
     self.diagnostic_codes = []
     self.use_phase_settings = use_phase_settings
     self.phase_setting = phase_setting
     self.input_signal = input_signal
     self.first_input = True
     self.print_output = print_output
Exemple #10
0
def part2():
    # 0 is black, 1 is white, and 2 is transparent
    input = [int(x) for x in get_input(8)[0]]
    length = 150  # 25 * 6
    master = [2] * 150
    layers = [input[i:i + 150] for i in range(0, len(input), 150)]
    for layer in layers:
        for i, num in enumerate(layer):
            if master[i] == 2:
                master[i] = num

    s = ''
    for i in range(length):
        if i % 25 == 0:
            s += "\n"
        s += str(master[i]) + " "

    print(s)
Exemple #11
0
def part1():
    wires, d = [], {}
    wires.extend(list(map(lambda wire: wire.split(','), get_input(3))))
    for i, wire in enumerate(wires):
        x = y = 0
        for instruction in wire:
            direction, distance = instruction[0], int(instruction[1:])
            if direction in ('L', 'R'):
                delta = (1 if direction == 'R' else -1, 0)
            else:
                delta = (0, 1 if direction == 'U' else -1)
            for _ in range(distance):
                x += delta[0]
                y += delta[1]
                if (x, y) not in d:
                    d[(x, y)] = {'seen': set(), 'm_dist': abs(x) + abs(y)}
                d[(x, y)]['seen'].add(i)

    intersections = list(
        filter(lambda coord: len(coord[1]['seen']) > 1, d.items()))
    return min(map(lambda coord: coord[1]['m_dist'], intersections))
Exemple #12
0
def test_regressions():
    assert part_1(lib.get_input(13)) == 1895
    assert part_2(lib.get_input(13)) == 840493039281088
Exemple #13
0
def part1():
    data = get_input(2)
    # before running the program, replace position 1 with the value 12 and replace position 2 with the value 2
    data[1] = 12
    data[2] = 2
    run(data)
Exemple #14
0
def part1():
    data = get_input(1)
    total_fuel_needed = 0
    for mass in data:
        total_fuel_needed += int(int(mass) / 3) - 2
    print(total_fuel_needed)
Exemple #15
0
 def calc(self):
     a, b, c = get_input('a: '), get_input('b: '), get_input('c: ')
     s = (a + b + c) / 2
     return (s * (s - a) * (s - b) * (s - c))**0.5
Exemple #16
0
def test_regression():
    assert part_1(SAMPLE) == 25
    assert part_2(SAMPLE) == 286

    assert part_1(lib.get_input(12)) == 2280
    assert part_2(lib.get_input(12)) == 38693
Exemple #17
0
    ticket_rules, your_ticket, other_tickets = parse_input(raw)

    bad_tickets = set(get_bad_tickets(ticket_rules, other_tickets))
    other_tickets = set(other_tickets) - bad_tickets

    constraints = {rule: set(range(len(your_ticket))) for rule in ticket_rules}

    while any(len(indices) != 1 for indices in constraints.values()):
        for rule in ticket_rules:
            for ticket in other_tickets:
                for index, num in enumerate(ticket):
                    if not rule.matches(num):
                        constraints[rule].discard(index)

            if len(constraints[rule]) == 1:
                index = list(constraints[rule])[0]
                for other_rule in ticket_rules:
                    if rule != other_rule:
                        constraints[other_rule].discard(index)

    defined = {list(indices)[0]: rule.name for rule, indices in constraints.items()}

    return lib.product(
        [val for i, val in enumerate(your_ticket) if defined[i].startswith("departure")]
    )


if __name__ == "__main__":
    print(part_1(lib.get_input(16)))
    print(part_2(lib.get_input(16)))
Exemple #18
0
 def calc(self) -> float:
     radius = get_input('Set radius: ')
     return radius**2 * pi
Exemple #19
0
    def execute(self):
        for id in self.pull:
            self.get_from_pull(id).hi()

        figure = self.get_from_pull(get_input('Select:'))
        print(figure.calc())
Exemple #20
0
            row.append(variation)

    for row in tile_grid:
        for t1, t2 in lib.window(row, 2):
            assert t1.right() == t2.left()

    for i in range(len(tile_grid)):
        column = [row[i] for row in tile_grid]
        for t1, t2 in lib.window(column, 2):
            assert t1.bottom() == t2.top()

    pixel_ids = [tile.tile_id for row in tile_grid for tile in row]
    assert len(set(pixel_ids)) == len(list(pixel_ids))

    tile_size = len(tiles[0].pixels)
    pixels: List[List[bool]] = []
    for row in tile_grid:
        for i in range(1, tile_size - 1):
            pixels.append([])
            for tile in row:
                for pixel in tile.pixels[i][1:-1]:
                    pixels[-1].append(pixel)

    mega_tile = ImageTile(1, tuple(tuple(row) for row in pixels))
    return min(map(count_monsters, mega_tile.variations()))


if __name__ == "__main__":
    print(part_1(lib.get_input(20)))
    print(part_2(lib.get_input(20)))
Exemple #21
0
        a, b = orbit.split(")")
        g[b] = {'planet': a, 'distance': None if a != "COM" else 1}
    return g


def calc_distance(planet):
    if graph[planet]['distance']:
        return graph[planet]['distance']
    else:
        graph[planet]['distance'] = calc_distance(graph[planet]['planet']) + 1
        return graph[planet]['distance']


def part1(graph):
    pprint(graph)
    for planet in filter(lambda p: graph[p]['distance'] is None, graph.keys()):
        calc_distance(planet)
    print(sum(map(lambda v: v['distance'], graph.values())))


def part2(graph):
    print("You are orbiting {}".format(graph['YOU']))
    print("Santa is orbiting {}".format(graph['SAN']))


if __name__ == "__main__":
    data = get_input(6)
    graph = build_graph(data)
    part1(graph)
    part2(graph)
Exemple #22
0
def prep_wires():
    data = get_input(3)
    wire1 = data[0].split(',')
    wire2 = data[1].split(',')
    data = [wire1, wire2]
    return data
Exemple #23
0
from lib import get_input


def get_clues(input):
    tens = 1
    units = 1
    row = col = None
    item = 11
    while tens != row or units != col:
        yield item
        row = tens
        col = units
        item = input[row - 1][col - 1]
        tens = item // 10
        units = item - (tens * 10)


if __name__ == '__main__':
    input = get_input()
    print(' '.join(map(str, get_clues(input))))
Exemple #24
0
 def calc() -> int:
     width, length = get_input('width: '), get_input('length: ')
     return width * length
Exemple #25
0
def test_regressions():
    assert part_1(lib.get_input(14)) == 13865835758282
    assert part_2(lib.get_input(14)) == 4195339838136
Exemple #26
0
        instruction, steps = line[0], int(line[1:])

        if instruction in "NESW":
            displacement = Orientation.from_char(instruction).as_coords().times(steps)
            self.waypoint = self.waypoint.displace(*displacement)
        elif instruction in "LR":
            degrees = -1 * steps if instruction == "R" else steps
            self.waypoint = self.waypoint.rotate(degrees)
        elif instruction == "F":
            displacement = self.waypoint.times(steps)
            self.position = self.position.displace(*displacement)

        return self


def part_1(raw: str):
    ship = ShipState()
    [ship.move(line) for line in raw.splitlines()]
    return Point(0, 0).manhattan_distance_to(ship.position)


def part_2(raw: str):
    ship = ShipState()
    [ship.move_waypoint(line) for line in raw.splitlines()]
    return Point(0, 0).manhattan_distance_to(ship.position)


if __name__ == "__main__":
    print(part_1(get_input(12)))
    print(part_2(get_input(12)))