advent_of_code_2023/Day04/python/solution1.py

67 lines
2.1 KiB
Python
Raw Normal View History

2023-12-04 08:21:10 +00:00
def parse_card_data(line):
"""Parse a single line of card data into card number, winning numbers, and own numbers."""
try:
2023-12-10 16:24:14 +00:00
card_info, number_parts = line.split(":")
winning_part, own_part = number_parts.split("|")
2023-12-04 08:21:10 +00:00
# Extract card number from card_info
2023-12-10 16:24:14 +00:00
card_number = "".join(filter(str.isdigit, card_info))
2023-12-04 08:21:10 +00:00
# Convert number strings to integer lists
winning_numbers = set(map(int, winning_part.split()))
own_numbers = list(map(int, own_part.split()))
2023-12-10 16:24:14 +00:00
print(
f"Card {card_number}: Winning Numbers: {winning_numbers}, Own Numbers: {own_numbers}"
)
2023-12-04 08:21:10 +00:00
return winning_numbers, own_numbers
except ValueError as e:
raise ValueError(f"Error parsing line '{line}': {e}")
2023-12-10 16:24:14 +00:00
2023-12-04 08:21:10 +00:00
def calculate_card_points(winning_numbers, own_numbers):
"""Calculate the points for a single card."""
points = 0
for number in own_numbers:
if number in winning_numbers:
points = 1 if points == 0 else points * 2
return points
2023-12-10 16:24:14 +00:00
2023-12-04 08:21:10 +00:00
def process_cards(file_path):
"""Process all cards in the given file and return the total points."""
total_points = 0
2023-12-10 16:24:14 +00:00
with open(file_path, "r") as file:
2023-12-04 08:21:10 +00:00
for line in file:
winning_numbers, own_numbers = parse_card_data(line.strip())
total_points += calculate_card_points(winning_numbers, own_numbers)
return total_points
2023-12-10 16:24:14 +00:00
2023-12-04 08:21:10 +00:00
def test():
"""Run tests using the test.txt file."""
expected_result = 13 # Based on the given example
2023-12-10 16:24:14 +00:00
result = process_cards("../test.txt")
assert (
result == expected_result
), f"Test failed: Expected {expected_result}, got {result}"
2023-12-04 08:21:10 +00:00
print(f"Test passed: {result} points")
2023-12-10 16:24:14 +00:00
2023-12-04 08:21:10 +00:00
def main():
"""Main function to process the input file and display results."""
try:
# Run tests first
test()
# Process actual input
2023-12-10 16:24:14 +00:00
total_points = process_cards("../input.txt")
2023-12-04 08:21:10 +00:00
print(f"Total points from input.txt: {total_points}")
except Exception as e:
print(f"An error occurred: {e}")
2023-12-10 16:24:14 +00:00
2023-12-04 08:21:10 +00:00
if __name__ == "__main__":
main()