advent-of-code-2023/7/a.py

72 lines
1.5 KiB
Python
Executable File

#!/usr/bin/env python3
from collections import Counter
from enum import IntEnum, auto
order = '23456789TJQKA'
class Hand(IntEnum):
HighCard = auto()
OnePair = auto()
TwoPair = auto()
ThreeKind = auto()
FullHouse = auto()
FourKind = auto()
FiveKind = auto()
def rank_card(card):
return order.find(card)
def evaluate(cards):
co = Counter(cards)
common = co.most_common()
ret = None
if common[0][1] == 5:
ret = Hand.FiveKind
elif common[0][1] == 4:
ret = Hand.FourKind
elif common[0][1] == 3 and common[1][1] == 2:
ret = Hand.FullHouse
elif common[0][1] == 3:
ret = Hand.ThreeKind
elif common[0][1] == 2 and common[1][1] == 2:
ret = Hand.TwoPair
elif common[0][1] == 2:
ret = Hand.OnePair
else:
ret = Hand.HighCard
ret = [int(ret)]
ret.extend([rank_card(card) for card in cards])
return tuple(ret)
def rank_hand(hand):
return evaluate(hand)
hands = {}
bids = {}
value = {}
with open('input.txt', mode='r') as f:
for line in f.readlines():
line = line[:-1]
hand, bid = line.split(' ', maxsplit=1)
bid = int(bid)
hands[hand] = hand
bids[hand] = bid
value[rank_hand(hand)] = hand
ranks = list(value.keys())
ranks.sort()
ranking = {k: ranks.index(k) + 1 for k in value.keys()}
winnings = {k: bids[k] * ranking[v] for v, k in value.items()}
for i in range(len(ranks)):
hand = value[ranks[i]]
print('hand', hand, 'is rank', i + 1, '=', ranks[i], f'bidding {bids[hand]}, and wins', winnings[hand])
print(sum(winnings.values()))