Created
December 21, 2023 23:00
-
-
Save BenBurnett/d4a75f0c5b207fe203c00363104f04f9 to your computer and use it in GitHub Desktop.
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
from collections import Counter | |
from enum import Enum | |
class HandType(Enum): | |
FIVE_OF_A_KIND = 7 | |
FOUR_OF_A_KIND = 6 | |
FULL_HOUSE = 5 | |
THREE_OF_A_KIND = 4 | |
TWO_PAIR = 3 | |
ONE_PAIR = 2 | |
HIGH_CARD = 1 | |
class Hand: | |
CARD_VALUES = {'T': 10, 'J': 1, 'Q': 12, 'K': 13, 'A': 14} | |
def __init__(self, hand: str) -> None: | |
self.hand, self.bid = hand.split() | |
self.bid = int(self.bid) | |
self.type: HandType = self._get_type(self.hand) | |
def __repr__(self) -> str: | |
return f'{self.hand}' | |
@staticmethod | |
def _get_type(hand: str) -> HandType: | |
j_count = hand.count('J') | |
counter = Counter(hand.replace('J', '') or 'J' * j_count) | |
sets = len(counter) | |
high = counter.most_common()[0][1] + j_count | |
if sets == 1: | |
return HandType.FIVE_OF_A_KIND | |
elif sets == 2 and high == 4: | |
return HandType.FOUR_OF_A_KIND | |
elif sets == 2: | |
return HandType.FULL_HOUSE | |
elif sets == 3 and high == 3: | |
return HandType.THREE_OF_A_KIND | |
elif sets == 3 and high == 2: | |
return HandType.TWO_PAIR | |
elif sets == 4: | |
return HandType.ONE_PAIR | |
else: | |
return HandType.HIGH_CARD | |
@staticmethod | |
def _compare_cards(left: str, right: str) -> bool: | |
return (Hand.CARD_VALUES.get(left) | |
or int(left)) < (Hand.CARD_VALUES.get(right) or int(right)) | |
def __lt__(self, other) -> bool: | |
if self.type.value != other.type.value: | |
return self.type.value < other.type.value | |
for i in range(5): | |
if self.hand[i] == other.hand[i]: | |
continue | |
return self._compare_cards(self.hand[i], other.hand[i]) | |
hands = sorted(Hand(line.strip()) for line in open('input/7.txt', 'r')) | |
print(sum((i + 1) * hand.bid for i, hand in enumerate(hands))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment