diff options
author | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-04 09:24:43 +0000 |
---|---|---|
committer | Tomasz Kramkowski <tomasz@kramkow.ski> | 2023-12-04 09:24:43 +0000 |
commit | 517fa9f7c8065d5215a25d7e381866dff7499f9b (patch) | |
tree | 6e6908f649698aacbc21fa3dd2a3d75858248b47 | |
parent | 79930810aad2e15ad1d1e3465e80d72bdd098866 (diff) | |
download | aoc2023-517fa9f7c8065d5215a25d7e381866dff7499f9b.tar.gz aoc2023-517fa9f7c8065d5215a25d7e381866dff7499f9b.tar.xz aoc2023-517fa9f7c8065d5215a25d7e381866dff7499f9b.zip |
day 4
-rw-r--r-- | 4.py | 40 |
1 files changed, 40 insertions, 0 deletions
@@ -0,0 +1,40 @@ +from dataclasses import dataclass +from functools import cache +from sys import stdin + + +@dataclass(frozen=True) +class Card: + id: int + winning: frozenset[int] + have: frozenset[int] + + @property + def nmatching(self) -> int: + return len(self.winning & self.have) + + @classmethod + def from_str(cls, s: str): + card, rest = s.split(": ") + _, card_id = card.split() + winning, have = rest.split(" | ") + return cls( + int(card_id), + frozenset(map(int, winning.split())), + frozenset(map(int, have.split())), + ) + + +cards = [Card.from_str(l.rstrip()) for l in stdin] +cards = {c.id: c for c in cards} + + +@cache +def p2_impl(card: Card) -> int: + return 1 + sum( + p2_impl(cards[cid]) for cid in range(card.id + 1, card.id + card.nmatching + 1) + ) + + +print(sum(int(2 ** (c.nmatching - 1)) for c in cards.values())) +print(sum(p2_impl(c) for c in cards.values())) |