Esempio n. 1
0
def part2():
    def get_all_flips_seamonster_count():
        seamonster_count = get_seamonster_count(image, seamonster)
        if seamonster_count == 0:
            # Flip horizontal
            seamonster_count = get_seamonster_count(flip_horizontal(image),
                                                    seamonster)
        if seamonster_count == 0:
            # Flip vertical
            seamonster_count = get_seamonster_count(flip_vertical(image),
                                                    seamonster)

        return seamonster_count

    tiles = get_tiles()
    seamonster = read_lines('Seamonster.txt')

    corners = [tile for tile in tiles if tile.get_match_count() == 2]

    image = generate_full_image(corners)

    seamonster_count = get_all_flips_seamonster_count()
    while seamonster_count == 0:
        image = rotate_90(image)
        seamonster_count = get_all_flips_seamonster_count()

    seamonster_hash_count = len(
        [char for char in ''.join(seamonster) if char == '#'])
    total_hash_count = len([char for char in ''.join(image) if char == '#'])
    final_count = total_hash_count - (seamonster_hash_count * seamonster_count)
    return final_count
Esempio n. 2
0
def process(is_valid):
    lines = read_lines('Input.txt')
    return len([
        policy_and_password
        for policy_and_password in [PolicyAndPassword(line) for line in lines]
        if is_valid(policy_and_password)
    ])
Esempio n. 3
0
def part2():
    lines = [int(line) for line in read_lines('Input.txt')]
    combos = list(combinations(lines, 2))
    print(combos)
    pair = [
        pair for pair in combos if remainder_in_list(pair[0] + pair[1], lines)
    ].pop()
    return pair[0] * pair[1] * (2020 - pair[0] - pair[1])
Esempio n. 4
0
def find_invalid():
    lines = [int(line) for line in read_lines('Input.txt')]
    invalid = -1
    countback = 25
    next_index = countback
    while invalid == -1:
        invalid = check_next(next_index, countback, lines)
        next_index += 1
    return invalid
Esempio n. 5
0
def part1():
    lines = [
        line.replace('\n', '').replace('"', '')
        for line in read_lines("Input.txt")
    ]
    rule_end_index = lines.index('')
    rules = lines[:rule_end_index]
    rule_map = {
        int(line.split(': ')[0]): line.split(': ')[1]
        for line in rules
    }
    regex = re.compile('^' + get_regex(rule_map[0], rule_map, 0) + '$')
    lines_to_validate = lines[rule_end_index + 1:]
    print(len([match for match in lines_to_validate if regex.match(match)]))
Esempio n. 6
0
def part1():
    lines = read_lines('Input.txt')
    target = int(lines[0])
    buses = [int(bus) for bus in lines[1].replace('x,', '').split(',')]

    bus_time_map = {}
    for bus in buses:
        running_total = 0
        while running_total < target:
            running_total += bus
        bus_time_map[running_total] = bus

    final_time = min(bus_time_map.keys())
    return (final_time - target) * bus_time_map[final_time]
Esempio n. 7
0
def part1():
    direction = EAST
    position = Point(START_POSITION.x, START_POSITION.y)
    lines = read_lines("Input.txt")
    for line in lines:
        instruction = line[0]
        amount = int(line[1:])
        if instruction in ["R", "L"]:
            direction = rotate(direction, instruction, amount)
        elif instruction in DIRECTIONS:
            position = move(position, DIRECTIONS.index(instruction), amount)
        else:
            position = move(position, direction, amount)

    return abs(position.x) + abs(position.y)
Esempio n. 8
0
def part1():
    line = [Entry(int(c)) for c in read_lines('Input.txt')[0]]

    populate_links(line)

    play_game(line, 100)

    cup_one = [cup for cup in line if cup.value == 1][0]
    next_cup = cup_one.next_cup
    result = ''
    while next_cup.value != 1:
        result += str(next_cup.value)
        next_cup = next_cup.next_cup

    print(result)
Esempio n. 9
0
def part2():
    line = [Entry(int(c)) for c in read_lines('Input.txt')[0]]

    max_num = max([int(e.value) for e in line])

    for i in range(max_num + 1, 1000001):
        line.append(Entry(i))

    populate_links(line)

    play_game(line, 10000000)

    cup_one = [cup for cup in line if cup.value == 1][0]
    result = cup_one.next_cup.value * cup_one.next_cup.next_cup.value
    # print(cup_one.next_cup.value)
    # print(cup_one.next_cup.next_cup.value)
    print(result)
Esempio n. 10
0
def part2():
    def get_prev(number):
        return [line for line in lines if line >= number - 3 and not line >= number]

    def process_next():
        number = lines[index]
        path_counts[number] = 0
        for prev in get_prev(number):
            path_counts[number] += path_counts[prev]

    lines = [int(row) for row in file_reader.read_lines('Input.txt')]
    lines.append(0)
    lines.sort()
    path_counts = {0: 1}
    for index in range(1, len(lines)):
        process_next()

    return path_counts[max(lines)]
Esempio n. 11
0
def part2():
    def has_count(bag):
        return bag != 'noother'

    def bags_within_bag_colour(bag_count_item):
        bag_count_list = [
            *[
                bag for bag in bag_map.get(bag_count_item[0]).split(',')
                if has_count(bag)
            ]
        ]
        return {
            bag[1:len(bag)]: int(bag[0]) * bag_count_item[1]
            for bag in bag_count_list
        }

    def bags_within_non_empty(bags_within):
        return len(bags_within) > 0

    def get_contained_directly(bag_count_items):
        return [
            bags_within for bags_within in [
                bags_within_bag_colour(bag_colour)
                for bag_colour in bag_count_items
            ] if bags_within_non_empty(bags_within)
        ]

    def populate_bag_list(bag_count_map):
        contained_directly = get_contained_directly(bag_count_map.items())

        if len(contained_directly) > 0:
            complete_list.extend(contained_directly)

        if len(contained_directly) > 0:
            for bag_count_direct_map in contained_directly:
                populate_bag_list(bag_count_direct_map)

    bag_map = get_bag_map(read_lines('Input.txt'))
    complete_list = []
    populate_bag_list({'shinygold': 1})
    return sum(
        chain.from_iterable({this_map.values()
                             for this_map in complete_list}))
Esempio n. 12
0
def parse_input(process):
    def parse_line():
        new_mask = mask
        parts = line.split(" = ")
        line_type = parts[0]
        if line_type == MASK:
            new_mask = parts[1].replace("\n", "")
        else:
            mem_address = parts[0].split("[")[1].replace("]", "")
            process(int(parts[1].replace("\n", "")), result, mem_address, new_mask)
        return new_mask

    lines = read_lines('Input.txt')
    mask = ""
    result = {}
    for line in lines:
        mask = parse_line()

    return sum(result.values())
Esempio n. 13
0
def process(upper):
    def take_turn():
        if turn < len(start_nums):
            next_num = start_nums[turn]
        else:
            next_num = turn - 1 - num_turn_map[
                last_num] if last_num in num_turn_map else 0

        num_turn_map[last_num] = turn - 1

        return next_num

    start_nums = [int(num) for num in read_lines("Input.txt")[0].split(",")]

    last_num = ""
    num_turn_map = {}
    for turn in range(0, upper):
        last_num = take_turn()

    return last_num
Esempio n. 14
0
def part2():
    lines = read_lines('Input.txt')
    buses = lines[1].split(',')
    bus_index_map = {
        int(bus): index
        for index, bus in enumerate(buses) if bus != 'x'
    }
    bus_list = [int(bus) for bus in buses if bus != 'x']
    bus_list.sort()
    bus_list.reverse()

    jump = 1
    answer = bus_list[0] - bus_index_map[bus_list[0]]
    for bus in bus_list:
        index = bus_index_map[bus]
        while (answer + index) % int(bus) != 0:
            answer += jump
        jump *= int(bus)

    return answer
Esempio n. 15
0
def part1():
    subject_number = 7

    lines = read_lines('Input.txt')
    card_pub_key = int(lines[0])
    door_pub_key = int(lines[1])

    value = 1
    card_loop_size = 0
    while value != card_pub_key:
        value *= subject_number
        value = value % 20201227
        card_loop_size += 1

    subject_number = door_pub_key
    enc_key = 1
    for i in range(0, card_loop_size):
        enc_key *= subject_number
        enc_key = enc_key % 20201227

    print(enc_key)
Esempio n. 16
0
def get_initial_state():
    black_tiles = set()
    lines = read_lines('Input.txt')

    for line in lines:
        char_index = 0
        x = 0
        y = 0
        while char_index < len(line):
            char = line[char_index]
            char_index += 1
            direction = char
            if char == 'n' or char == 's':
                direction += line[char_index]
                char_index += 1

            if direction == 'e':
                x += 2
            elif direction == 'se':
                x += 1
                y -= 1
            elif direction == 'sw':
                x -= 1
                y -= 1
            elif direction == 'w':
                x -= 2
            elif direction == 'nw':
                x -= 1
                y += 1
            elif direction == 'ne':
                x += 1
                y += 1

        point = Point(x, y)
        if point in black_tiles:
            black_tiles.remove(point)
        else:
            black_tiles.add(point)

    return black_tiles
Esempio n. 17
0
def get_all_ingredients_and_allergen_map():
    lines = read_lines('Input.txt')

    allergen_to_ingredient = {}
    all_ingredients = list()

    for line in lines:
        contains_str = ' (contains '
        contains_index = line.index(contains_str)
        ingredients = line[:contains_index]
        allergens = line[contains_index + len(contains_str):].replace(
            ',', '').replace(')', '')
        ingredient_set = set(ingredients.split(' '))
        all_ingredients.extend(list(ingredient_set))
        for allergen in allergens.split(' '):
            if allergen in allergen_to_ingredient.keys():
                allergen_to_ingredient[allergen] = set.intersection(
                    ingredient_set, allergen_to_ingredient[allergen])
            else:
                allergen_to_ingredient[allergen] = ingredient_set

    return [all_ingredients, allergen_to_ingredient]
Esempio n. 18
0
def part2():
    waypoint_relative = Point(10, 1)
    ship_position = Point(START_POSITION.x, START_POSITION.y)
    waypoint_position = Point(START_POSITION.x + waypoint_relative.x, START_POSITION.y + waypoint_relative.y)
    lines = read_lines("Input.txt")
    for line in lines:
        instruction = line[0]
        amount = int(line[1:])

        if instruction in ["R", "L"]:
            waypoint_position = rotate_waypoint(waypoint_position, ship_position, instruction, amount)
            waypoint_relative = Point(waypoint_position.x - ship_position.x, waypoint_position.y - ship_position.y)

        elif instruction in DIRECTIONS:
            waypoint_position = move(waypoint_position, DIRECTIONS.index(instruction), amount)
            waypoint_relative = Point(waypoint_position.x - ship_position.x, waypoint_position.y - ship_position.y)
        else:
            for i in range(0, amount):
                ship_position = Point(waypoint_position.x, waypoint_position.y)
                waypoint_position = Point(ship_position.x + waypoint_relative.x, ship_position.y + waypoint_relative.y)

    return abs(ship_position.x) + abs(ship_position.y)
Esempio n. 19
0
def part1():
    def add_next():
        prev = chain[-1]
        diff = 1
        while True:
            for line in lines:
                if prev + diff == line:
                    chain.append(line)
                    return diff
            diff += 1

    lines = [int(row) for row in file_reader.read_lines('Input.txt')]
    chain = [0]
    one_diff = 0
    three_diff = 0
    while max(chain) != max(lines):
        next_diff = add_next()
        if next_diff == 1:
            one_diff += 1
        if next_diff == 3:
            three_diff += 1
    return one_diff * (three_diff + 1)
Esempio n. 20
0
def part1():
    def bags_containing_bag_colour(bag_colour):
        return [
            key for key in bag_map.keys() if bag_colour in bag_map.get(key)
        ]

    def populate_bag_list(bag_list):
        if len(bag_list) == 0:
            return

        contain_directly = [
            *chain.from_iterable([
                bags_containing_bag_colour(bag_colour)
                for bag_colour in bag_list
            ])
        ]
        complete_bag_list.update(contain_directly)
        populate_bag_list(contain_directly)

    bag_map = get_bag_map(read_lines('Input.txt'))
    complete_bag_list = set()
    populate_bag_list(['shinygold'])

    return len(complete_bag_list)
Esempio n. 21
0
def part2():
    sum_str_lines = read_lines('Input.txt')
    return sum([calc_sum_part2(line.replace(' ', '').replace('\n', ''), True)[0] for line in sum_str_lines])
Esempio n. 22
0
def get_seat_ids() -> list:
    return [get_seat_id(line) for line in read_lines('Input.txt')]
Esempio n. 23
0
 def __init__(self, filename):
     self.lines = read_lines(filename)
Esempio n. 24
0
def read_hands():
    lines = read_lines('Input.txt')
    player2_index = lines.index('Player 2:')
    player1_cards = [int(line) for line in lines[1:player2_index - 1]]
    player2_cards = [int(line) for line in lines[player2_index + 1:]]
    return [player1_cards, player2_cards]
Esempio n. 25
0
def part2():
    lines = [int(line) for line in read_lines('Input.txt')]
    number_to_find = find_invalid()
    contiguous_set = find_contiguous_set(lines, number_to_find)
    return min(contiguous_set) + max(contiguous_set)
Esempio n. 26
0
def part1():
    lines = [int(line) for line in read_lines('Input.txt')]
    match = [number for number in lines
             if remainder_in_list(number, lines)].pop()
    return match * (2020 - match)