Untitled

 avatar
unknown
plain_text
a year ago
2.2 kB
5
Indexable
from collections import Counter
from functools import cmp_to_key

def main():
    with open('input.txt', 'r') as file:
        lines = file.readlines()
        hands_and_bids = []

        for line in lines:
            hand, bid = line.split()
            hands_and_bids.append((hand, int(bid)))

    ordered_hands = sorted(hands_and_bids, key=cmp_to_key(compare_hands))

    count = 0
    for idx, hand in enumerate(ordered_hands, start=1):
        count += idx * hand[1]
    print(count)
    print(ordered_hands)

def compare_hands(hand_1, hand_2):
    """Compare two hands and return -1, 0, or 1 based on their strength."""
    count_hand_1, count_hand_2 = Counter(hand_1[0]), Counter(hand_2[0])
    if hand_type(count_hand_1) > hand_type(count_hand_2):
        return 1
    elif hand_type(count_hand_1) < hand_type(count_hand_2):
        return -1
    else:
        score_order = "23456789TJQKA"
        for card_1, card_2 in zip(hand_1[0], hand_2[0]):
            if card_1 not in score_order or card_2 not in score_order:
                raise ValueError(f"Invalid card label: {card_1} or {card_2}")
            if card_value(card_1) > card_value(card_2):
                return 1
            elif card_value(card_1) < card_value(card_2):
                return -1
        # If all of the cards are the same
        return 0

def card_value(card):
    score_order = "23456789TJQKA"
    return score_order.index(card)

def hand_type(hand):
    """Determine the type of a hand based on its card distribution."""
    count_hand = sorted(Counter(hand).values(), reverse=True)
    match count_hand:
        # High card
        case [1, 1, 1, 1, 1]:
            return 0  
        # 1 pair
        case [2, 1, 1, 1]:
            return 1
        # 2 pairs
        case [2, 2, 1]:
            return 2 
        # 3 of a kind
        case [3, 1, 1]:
            return 3
        # Full house
        case [3, 2]:
            return 4
        # 4 of a kind
        case [4, 1]:
            return 5
        # 5 of a kind
        case [5]:
            return 6

        # Unknown hand type
        case _:
            return -1  


if __name__ == "__main__":
    main()
    
Editor is loading...
Leave a Comment