My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add solution for 2023/07

+63
+63
2023/day07.py
··· 1 + import fileinput 2 + from collections import Counter 3 + 4 + 5 + def rank(hand, part_2=False): 6 + # Special-case JJJJJ; other hands Js just become the most common card. 7 + if part_2 and hand != 'JJJJJ': 8 + no_jokers = Counter(c for c in hand if c != 'J').most_common() 9 + hand = hand.replace('J', no_jokers[0][0]) 10 + 11 + cmn = Counter(hand).most_common() 12 + 13 + # Five of a Kind 14 + if cmn[0][1] == 5: 15 + return 6 16 + 17 + # Four of a Kind 18 + elif cmn[0][1] == 4: 19 + return 5 20 + 21 + # Full House / Three of a Kind (based on second-most common card) 22 + elif cmn[0][1] == 3: 23 + return 2 + cmn[1][1] 24 + 25 + # Two Pair / One Pair (based on second-most common card) 26 + elif cmn[0][1] == 2: 27 + return cmn[1][1] 28 + 29 + return 0 30 + 31 + 32 + def tiebreak(hand, part_2=False): 33 + return tuple(card_score(c, part_2) for c in hand) 34 + 35 + 36 + def card_score(card, part_2=False): 37 + if part_2: 38 + return 'J23456789TQKA'.index(card) 39 + else: 40 + return '23456789TJQKA'.index(card) 41 + 42 + 43 + # Parse problem input. 44 + hands = [] 45 + for line in fileinput.input(): 46 + hand, bid = line.split() 47 + hands.append((hand, int(bid))) 48 + 49 + 50 + # Solve part 1. 51 + part_1 = 0 52 + for i, (hand, bid) in enumerate(sorted(hands, key=lambda h: (rank(h[0]), tiebreak(h[0]))), start=1): 53 + part_1 += i * bid 54 + 55 + print("Part 1:", part_1) 56 + 57 + 58 + # Solve part 2. 59 + part_2 = 0 60 + for i, (hand, bid) in enumerate(sorted(hands, key=lambda h: (rank(h[0], part_2=True), tiebreak(h[0], part_2=True))), start=1): 61 + part_2 += i * bid 62 + 63 + print("Part 2:", part_2)