Created
December 4, 2023 21:17
-
-
Save kstrauser/2c3f76ca3fc5009f67a650bffefc595d to your computer and use it in GitHub Desktop.
advent2023day4p2.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from functools import cache | |
real = True | |
with open("real_1.txt" if real else "test_1.txt") as infile: | |
data = infile.read().strip() | |
def matches_in(card): | |
card_num, numbers = card.strip().split(": ") | |
they, me = numbers.split(" | ") | |
they_have = {int(_) for _ in they.split()} | |
i_have = {int(_) for _ in me.split()} | |
matches = len(they_have & i_have) | |
return int(card_num.split()[1]), matches | |
cards = {} | |
for card in data.splitlines(): | |
card_num, matches = matches_in(card) | |
cards[card_num] = matches | |
@cache | |
def score(card_num): | |
matches = cards[card_num] | |
if not matches: | |
return 1 | |
return 1 + sum(score(card_num + n + 1) for n in range(matches)) | |
print(sum(score(card_num) for card_num in cards.keys())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment