Exemple #1
0
def get_parsed_input2(file_name):
    l = get_list(file_name)[1].split(',')
    pairs = [(t[0], int(t[1])) for t in enumerate(l) if t[1] != 'x']
    # alternative calculation
    # pairs2 = filter(lambda t: t[1] != 'x', enumerate(l))
    # pairs2 = map(lambda t: (t[0], int(t[1])), pairs2)
    return pairs
Exemple #2
0
def get_parsed_input(file_name):
    l = get_list(file_name)
    mask_mem_items = []
    for i in l:
        if i[:2] == 'ma':
            mask = re.search(r'[X01]{36}', i).group()
            mask_mem_items.append([mask])
        else:
            mem_pair = [int(n) for n in re.findall(r'[0-9]+', i)]
            mask_mem_items[-1].append(mem_pair)
    return mask_mem_items
Exemple #3
0
def parse_ticket_data(file) -> ({str: [range]}, [[int]]):
    all_data = get_list(file)
    ticket_fields_lines = range(20)
    my_ticket_line = (21)
    nearby_tickets_lines = (24, 264)
    ticket_fields = {}

    for ticket_field in ticket_fields_lines:
        field = re.search(r'[\w\s]+', all_data[ticket_field]).group()
        ranges = [int(n) for n in re.findall(r'\d+', all_data[ticket_field])]
        ranges = [
            range(ranges[i], ranges[i + 1] + 1) for i in range(len(ranges))
            if i % 2 == 0
        ]
        ticket_fields[field] = ranges

    nearby_tickets = [[int(n) for n in re.findall(r'\d+', nearby_ticket)]
                      for nearby_ticket in all_data[nearby_tickets_lines[0] -
                                                    1:nearby_tickets_lines[1]]]
    my_ticket = [int(n) for n in re.findall(r'\d+', all_data[my_ticket_line])]
    return ticket_fields, nearby_tickets, my_ticket
Exemple #4
0
def count_unique(s: str) -> int:
    unique = set(s)
    if ' ' in unique:
        unique.remove(' ')
    return len(unique)


def answered_by_all(s: str) -> int:
    qs = s.split()
    qs_sets = []
    for q in qs:
        qs_sets.append(set(q))
    qs_intersection = set.intersection(*qs_sets)
    return len(qs_intersection)


if __name__ == '__main__':
    l = get_list('input6.txt')
    print(l)
    group_qs = divide_passwords(l)
    print(group_qs)
    unique = []
    for i in group_qs:
        unique.append(count_unique(i))
    print(unique, '\n', sum(unique))
    everyone_answered = []
    for i in group_qs:
        everyone_answered.append(answered_by_all(i))
    print(everyone_answered, '\n', sum(everyone_answered))
Exemple #5
0
def get_parsed_input(file_name):
    l = get_list(file_name)
    return [int(l[0])] + [[int(n) for n in re.findall(r'\d+', l[1])]]
Exemple #6
0
def apply_rules(current_black_tiles: set, steps: int) -> int:
    new_white, new_black = set(), set()
    black_tiles = current_black_tiles.copy()
    white_tiles = set()
    for step in range(steps):
        for black_tile in black_tiles:
            all_neighbours = get_neighbours(black_tile)
            black_neighbours = all_neighbours & black_tiles
            white_neighbours = all_neighbours - black_tiles
            white_tiles.update(white_neighbours)
            if 0 < len(black_neighbours) <= 2:
                new_black.add(black_tile)
        for white_tile in white_tiles:
            all_neighbours = get_neighbours(white_tile)
            black_neighbours = all_neighbours & black_tiles
            if len(black_neighbours) == 2:
                new_black.add(white_tile)
        black_tiles = new_black.copy()
        white_tiles.clear()
        new_black.clear()
    return len(black_tiles)


if __name__ == '__main__':
    directions = get_list('input24.txt')
    black_tiles = black_tiles(directions)
    print(len(black_tiles))  # part 1 solution
    black_num = apply_rules(black_tiles, 100)
    print(black_num)  # part 2 solution
Exemple #7
0
    if isinstance(nested_list[0], list):
        return flatten(nested_list[0]) + flatten(nested_list[1:])
    return nested_list[:1] + flatten(nested_list[1:])


def find_outer(colour: str, bags: dict):
    return [[outer_colour] + find_outer(outer_colour, bags)
            for outer_colour, inner_colours in bags.items()
            if colour in inner_colours]


def count_inner(colour: str, bags: {str: [(int, str)]}) -> [int]:
    if len(bags[colour]) == 0: return 0
    return sum([c[0] + c[0] * count_inner(c[1], bags) for c in bags[colour]])


if __name__ == '__main__':
    l = get_list('input7.txt')
    print(l)
    bags_dict = get_dict(l)
    print(bags_dict)
    bags_colours = dict_only_colours(bags_dict)
    print(bags_colours)
    check_colour = find_outer('shiny gold', bags_colours)
    fl = flatten(check_colour)
    outer_colours = set(fl)
    print(outer_colours)
    print(len(outer_colours))
    inner_count = count_inner('shiny gold', bags_dict)
    print(inner_count)
Exemple #8
0
            else:
                cards_player2 += [card_player2, card_player1]
        elif first_bigger(card_player1, card_player2):
            cards_player1 += [card_player1, card_player2]
        else:
            cards_player2 += [card_player2, card_player1]

    if len(cards_player1) == 0:
        return [], cards_player2
    return cards_player1, []


def count_result(cards: [int]) -> int:
    return sum([cards[ind] * (len(cards) - ind) for ind in range(len(cards))])


if __name__ == '__main__':
    cards = get_list('input22.txt')
    player1 = str_to_list(cards[1:len(cards) // 2])
    player2 = str_to_list(cards[len(cards) // 2 + 2:])
    winner_cards = combat(player1, player2)
    print(count_result(winner_cards))

    player1_r = str_to_list(cards[1:len(cards) // 2])
    player2_r = str_to_list(cards[len(cards) // 2 + 2:])
    recursive_winner = resursive_combat(player1_r, player2_r, set())
    if recursive_winner[0] != []:
        print(count_result(recursive_winner[0]))
    else:
        print(count_result(recursive_winner[1]))
Exemple #9
0
                left = True
            elif exp[left_ind - 1] == '(':
                par_opened += 1
                left_ind -= 1
            elif exp[left_ind] == ')':
                par_closed += 1
                left_ind -= 1
            else:
                left_ind -= 1
        while not right:
            if right_ind + 1 == len(exp) or (par_opened == par_closed and exp[right_ind + 1] in ')+*'):
                right = True
            elif exp[right_ind] == '(':
                par_opened += 1
                right_ind += 1
            elif exp[right_ind + 1] == ')':
                par_closed += 1
                right_ind += 1
            else:
                right_ind += 1
        exp = exp[:left_ind] + '(' + exp[left_ind:right_ind + 1] + ')' + exp[right_ind + 1:]
    return exp


if __name__ == '__main__':
    operations = get_list('input18.txt')
    part1_operations = sum([calculate(expression) for expression in operations])
    operations_plus_priority = [add_addition_priority(exp) for exp in operations]
    part2_operations = sum([calculate(expression) for expression in operations_plus_priority])
    print(part1_operations, part2_operations)
Exemple #10
0
def get_rules(file) -> dict:
    rules_list = get_list(file)
    rules = {rule_num: ' ' + val + ' ' for (rule_num, val) in [rule.split(':') for rule in rules_list]}
    return rules
Exemple #11
0
    rules = {rule_num: ' ' + val + ' ' for (rule_num, val) in [rule.split(':') for rule in rules_list]}
    return rules


def define_rule_0(rules: {str: str}) -> str:
    zero = rules['0']
    defined = zero[:]
    while re.search(r'\d', defined):
        numbers = re.findall(r'\d+', defined)
        for number in numbers:
            replacer = ' ( ' + rules[number] + ' ) '
            defined = re.sub(' ' + number + ' ', replacer, defined)
    return defined


def check(rule: str, messages: [str]) -> int:
    rule = re.sub(r'[\s"]', '', rule)
    rule = '^' + rule + '$'
    correct = [True for message in messages if re.search(rule, message)]
    return sum(correct)


if __name__ == '__main__':
    messages = get_list('input19_messages.txt')
    rules = get_rules('input19_rules.txt')
    print(check(define_rule_0(rules), messages))  # part 1 solution
    rules2 = dict(rules)
    rules2['8'] = '( 42 )+'
    rules2['11'] = ' 42 31 | 42 42 31 31 | 42 42 42 31 31 31 | 42 42 42 42 31 31 31 31 | 42 42 42 42 42 31 31 31 31 31 '
    print(check(define_rule_0(rules2), messages))  # part 2 solution
Exemple #12
0
        return min_position
    return -1


def count_seat_ID(row: int, column: int, multiplier: int):
    return row * multiplier + column


def find_seat(IDs: list) -> int:
    ordered = sorted(IDs)
    for i in range(len(ordered) - 2):
        i1 = ordered[i]
        i2 = ordered[i + 1]
        if i2 - i1 == 2:
            return (i2 + i1) // 2
    return -1


if __name__ == '__main__':
    boarding_passes = get_list('input5.txt')
    print(boarding_passes)
    IDs = []
    for bp in boarding_passes:
        row = decipher_row_num(bp, 128, 7)
        column = decipher_column_num(bp, 8, 3)
        IDs.append(count_seat_ID(row, column, 8))
    print(IDs)
    print(max(IDs))
    my_seat = find_seat(IDs)
    print(my_seat)
Exemple #13
0
                    get_closest_occupied(old_seats, current_seat, (1, 1))
                ]

                if is_free(old_seats, (row, column)):
                    if '#' not in sides:
                        new_s = seats[row][:column] + '#' + seats[row][column +
                                                                       1:]
                        seats[row] = new_s
                        moved = True
                elif is_occupied(old_seats, (row, column)):
                    occupied = Counter(sides)['#']
                    if occupied >= 5:
                        new_s = seats[row][:column] + 'L' + seats[row][column +
                                                                       1:]
                        seats[row] = new_s
                        moved = True
    return seats


def count_ch(l: [[str]]) -> int:
    return sum([Counter(row)['#'] for row in l])


if __name__ == '__main__':
    rows = get_list('input11.txt')
    new_rows = add_edges(rows)
    after_simulation = seats_simulation(new_rows)
    print(count_ch(after_simulation))
    after_simulation2 = seats_simulation2(new_rows)
    print(count_ch(after_simulation2))
Exemple #14
0
    while not fixed:
        while ind < len(bool_list) and bool_list[ind]:
            bool_list[ind] = False
            res, ind = implement_rules(instructions_copy[ind][0], instructions_copy[ind][1], instructions_copy[ind][2],
                                       res, ind)
        if ind == len(instructions_copy):
            fixed = True
        else:
            if potential_change_ind < len(potential_changes) - 1:
                potential_change_ind += 1
                fix_ind = potential_changes[potential_change_ind]
                instructions_copy = instructions[:]
                instructions_copy[fix_ind] = (
                    changes[instructions[fix_ind][0]], instructions[fix_ind][1], instructions[fix_ind][2])
                res, ind = 0, 0
                bool_list = [True] * len(instructions)
            else:
                fixed = True
    return res


if __name__ == '__main__':
    instruction_list = get_list('input8.txt')
    print(instruction_list)
    instruction_list_parsed = parse_instr(instruction_list)
    print(instruction_list_parsed)
    value_before_repetition = run_boot_code(instruction_list_parsed)
    print(value_before_repetition)
    fixed_res = fix_boot_code(instruction_list_parsed)
    print(fixed_res)
Exemple #15
0
        for pair in pairs:
            if len(pair[1]) == 1:
                ingredient = pair[1].pop()
                found.append([pair[0], ingredient])
                pairs.remove(pair)
                if ingredient in ingredients_no_allergens:
                    ingredients_no_allergens.remove(ingredient)
                for remaining in pairs:
                    if ingredient in remaining[1]:
                        remaining[1].remove(ingredient)
    count_occurrences = sum([
        Counter(dish)[ingredient] for dish in food.values()
        for ingredient in ingredients_no_allergens
    ])
    return found, count_occurrences


def get_ingredients_list_sorted_by_allergen(pairs: [[str]]) -> str:
    sorted_pairs = sorted(pairs)
    return ','.join([pair[1] for pair in sorted_pairs])


if __name__ == '__main__':
    dishes = parse_food_list(get_list('input21.txt'))
    pairs_found, occurrences_ingredients_no_allergens = find_food_with_no_alergens(
        dishes)  # part 1 solution
    print(occurrences_ingredients_no_allergens)
    ingredients_left = get_ingredients_list_sorted_by_allergen(
        pairs_found)  # part 2 solution
    print(ingredients_left)