Untitled

mail@pastecode.io avatar
unknown
python
7 months ago
1.5 kB
4
Indexable
Never
def process_input_file(input_filename):
    data = {}
    with open(input_filename, 'r') as fh:
        for line in fh:
            (card_num, numbers) = line.strip().split(":")
            # grab the card number in case we need it later
            # it uses spaces to align
            card_num = int(card_num.split(" ")[-1])
            (winning_nums, our_nums) = numbers.split("|")
            winning_nums = [int(n) for n in winning_nums.split(" ") if n != ""]
            our_nums = [int(n) for n in our_nums.split(" ") if n != ""]
            data[card_num] = {"winning_numbers": winning_nums, "revealed_numbers": our_nums, "number_of_cards": 1}
    return data

def get_number_of_matches(data):
    results = {}
    for (card_num, game_data) in data.items():
        matches = 0
        for n in game_data["revealed_numbers"]:
            if n in game_data["winning_numbers"]:
                matches += 1
        # for every n matches, the next n cards get another card added to them
        for m in range(1, 1 + matches):
            next_game_num = card_num + m
            if next_game_num in data:
                data[next_game_num]["number_of_cards"] += game_data["number_of_cards"]
        results[card_num] = game_data["number_of_cards"]
    return results

if __name__ == "__main__":
    data = process_input_file("p4_input.txt")
    results = get_number_of_matches(data)
    print(sum(results.values()))
Leave a Comment