Esempio n. 1
0
def main(settings):
    """."""
    files = recursive_glob(settings['source_dir'], settings['filter'])
    patterns = extract_patterns(get_lines_from_file(settings['patterns']),
                                settings['sep'])

    for filename in files:
        lines = get_lines_from_file(filename)
        for search, replace in patterns:
            lines = search_and_replace_lines(search, replace, lines)

        write_lines_to_file(filename, lines)
Esempio n. 2
0
def solution2():
    values = get_lines_from_file('inputs/day1.txt')
    values = [int(val) for val in values]
    sorted_values = sorted(values)
    sorted_values_trimmed = sorted([
        val for val in values
        if (val + sorted_values[0] + sorted_values[1] < 2020)
    ])

    saved1 = 0
    saved2 = 0
    saved3 = 0
    exit = False
    for val1 in sorted_values_trimmed:
        if exit is True:
            break
        for val2 in sorted_values_trimmed:
            if exit is True:
                break
            if val1 + val2 > 2020:
                break
            for val3 in sorted_values_trimmed:
                if val1 + val2 + val3 == 2020:
                    saved1 = val1
                    saved2 = val2
                    saved3 = val3
                    exit = True
                    break
                if val1 + val2 + val3 > 2020:
                    break
    return (saved1, saved2, saved3, saved1 + saved2 + saved3,
            saved1 * saved2 * saved3)
Esempio n. 3
0
def solution1():
    values = get_lines_from_file('inputs/day1.txt')
    values = [int(val) for val in values]
    sorted_values = sorted(values)
    total = 0
    saved_val1 = 0
    saved_val2 = 0
    for val1 in sorted_values:
        if total == 2020:
            break
        for val2 in reversed(sorted_values):
            total = val1 + val2
            if total <= 2020:
                saved_val1 = val1
                saved_val2 = val2
                break

    return (saved_val1, saved_val2, saved_val1 + saved_val2,
            saved_val1 * saved_val2)
def start_from_dir():
    chessboards_dir = '/mnt/g/Documents/Chess/1001 Chess Exercises for Club Players/output/cb_sample_300/'
    chessboard_images = utils.get_filenames_from_dir(chessboards_dir)
    chessboard_images.sort(key=utils.alphanum_key)

    fen_list = utils.get_lines_from_file('./sample_data/fen-201-300.txt')
    print(chessboard_images)
    for i in range(len(chessboard_images)):

        img_path = Path(chessboards_dir).joinpath(chessboard_images[i])
        img = Image.open(img_path)
        img = img.resize((512, 512))
        arr = np.asarray(img)
        tiles = tile_splitter.split_img(arr, 64, 64)
        fen = expand_fen(fen_list[i])
        tiles = enumerate(tiles)
        print(i, chessboard_images[i], fen_list[i])

        for count, tile in tiles:
            tile_img = Image.fromarray(np.uint8(tile))
            fen_folder_name = f'./test/data/_{fen[count]}'
            Path(fen_folder_name).mkdir(parents=True, exist_ok=True)
            tile_img.save(
                f'{fen_folder_name}/{chessboard_images[i]}-{count}.jpg')
Esempio n. 5
0
            is_valid = False
            break
    return is_valid


def extract_items_from_passport(passport):
    passport = passport.replace('\n', " ")
    elements = passport.split(' ')
    items = {}
    for elt in elements:
        parts = elt.split(':')
        if len(parts) < 2:
            continue
        items[parts[0]] = parts[1]
    return items


def solution(passports):
    valid_count = 0
    for passport in passports:
        if is_valid_passport(passport):
            valid_count += 1

    return valid_count


if __name__ == '__main__':
    passports = get_lines_from_file('inputs/day4.txt', sep="\n\n")
    print(
        f"Found {solution(passports)} valid passports out of {len(passports)}")
Esempio n. 6
0
        parent_color, children_colors = parse_rule(rule)
        nodes_index[parent_color] = Node(parent_color)

    # Connect them together now by iterating a second time
    for rule in rules:
        parent_color, children_tuples = parse_rule(rule)
        parent_node = nodes_index[parent_color]
        for child_tuple in children_tuples:
            child_node = nodes_index[child_tuple[1]]
            parent_node.add_child(child_node, int(child_tuple[0]))
            child_node.add_parent(parent_node)
    return nodes_index


if __name__ == '__main__':
    rules = get_lines_from_file('inputs/day7.txt')
    print(f"Found a total of {len(rules)} bag colors")

    nodes_index = create_graph(rules)

    # Traverse the tree starting at shiny gold to get all parents
    parents_visited = set()

    def traverse_parents_from(node):
        if node.color in parents_visited:
            return
        parents_visited.add(node.color)

        for parent_node in node.parents:
            traverse_parents_from(parent_node)
Esempio n. 7
0
from utils import get_lines_from_file

if __name__ == '__main__':
    lines = get_lines_from_file('inputs/day6.txt', sep='\n\n')
    total = 0

    # Part 1
    for group in lines:
        unique_question_answers = set([char for char in group if char != "\n"])
        total += len(unique_question_answers)
    print(f"Found a total of {total} unique answers for all groups")

    # Part 2, let's use sets and do their intersection for each group
    # then we simply do the sum of the length of all the intersections
    intersection_total = 0
    for group in lines:
        one_person_answers = [elt for elt in group.split('\n') if elt]
        intersection_for_group = set(one_person_answers[0])
        for one_answer in one_person_answers:
            intersection_for_group = intersection_for_group.intersection(
                set(one_answer))
        intersection_total += len(intersection_for_group)

    print(
        f"Found an intersection total of {intersection_total} common answers")
Esempio n. 8
0
            if current_state[i][j] == OCCUPIED:
                counter += 1
    print(f"Counted {counter} occupied seats (V1)")


def solve_v2(current_state):
    while True:
        # print_state(current_state)  # use to debug
        next_state = get_next_state_v2(current_state)
        if next_state == current_state:
            break
        current_state = next_state

    print("The state has converged. Counting...")
    counter = 0
    for i in range(len(current_state)):
        for j in range(len(current_state[0])):
            if current_state[i][j] == OCCUPIED:
                counter += 1
    print(f"Counted {counter} occupied seats (V2)")


if __name__ == '__main__':
    lines = get_lines_from_file('inputs/day11.txt')
    current_state = state_from_input(lines)

    solve_v1(current_state)

    current_state = state_from_input(lines)
    solve_v2(current_state)