day 7, saved by Counter

This commit is contained in:
2025-09-08 01:46:10 +02:00
parent 6fe70f851f
commit d165384617
3 changed files with 116 additions and 0 deletions

56
d07/part1.py Normal file
View File

@@ -0,0 +1,56 @@
import sys
from collections import Counter as C
from functools import cmp_to_key as ctk
def score(h:str) -> int: # get type of a hand
D = C(h)
E = C(v for k,v in D.items())
if 5 in E: # five of a kind
return 7
elif 4 in E: # four of a kind
return 6
elif 3 in E and 2 in E: # full house
return 5
elif 3 in E: # three of a kind
return 4
elif 2 in E and E[2] == 2: # two pairs
return 3
elif 2 in E:
return 2
else: # high card
return 1
H = list(reversed('AKQJT98765432'))
def compareH(h1, h2):
for a,b in zip(h1,h2):
if H.index(a) < H.index(b):
return 1
elif H.index(a) > H.index(b):
return -1
return 0
def compare(T1, T2): # return >:-1, ==:0, <:1
h1, s1, *_ = T1
h2, s2, *_ = T2
s1 = score(h1)
s2 = score(h2)
if s1 < s2:
return 1
elif s2 < s1:
return -1
else:
return compareH(h1,h2)
L = [ l.split() for l in sys.stdin.read().splitlines()]
L = [[h,int(b)] for [h,b] in L]
for h,b in L:
print(h, score(h))
pass
L.sort(key=ctk(compare))
print(
sum((i+1)*b for i,(h,b) in enumerate(reversed(L)))
)

42
d07/part2.py Normal file
View File

@@ -0,0 +1,42 @@
import sys
from collections import Counter as C
from functools import cmp_to_key as ctk
H = list(reversed('AKQT98765432J'))
def score(h:str) -> int:
D = C(h)
j = D['J']
del D['J']
if j<5:
m = max(D.values())
for k,v in D.items():
if v == m:
D[k] = v+j
break
E = C(v for k,v in D.items()) if j<5 else {5:1}
r = 0
if 5 in E: # five of a kind
r = 7
elif 4 in E: # four of a kind
r = 6
elif 3 in E and 2 in E: # full house
r = 5
elif 3 in E: # three of a kind
r = 4
elif 2 in E and E[2] == 2: # two pairs
r = 3
elif 2 in E: # one pair
r = 2
else: # high card
r = 1
return (r, *[H.index(c) for c in h])
L = [ l.split() for l in sys.stdin.read().splitlines()]
L = [(score(h),int(b)) for [h,b] in L]
sorted(L)
print(
sum((i+1)*b for i,(h,b) in enumerate(reversed(L)))
)

18
d07/terse.py Normal file
View File

@@ -0,0 +1,18 @@
from collections import Counter
lines = [i for i in open('input').read().split('\n') if i.strip()]
def hand(h,part1):
if part1: h = h.replace('J', 'X')
h2 = ['J23456789TXQKA'.index(i)for i in h]
ts = []
for r in '23456789TQKA':
c = Counter(h.replace('J', r))
p = tuple(sorted(c.values()))
t = [(1,1,1,1,1),(1,1,1,2),(1,2,2),(1,1,3),(2,3),(1,4),(5,)].index(p)
ts.append(t)
return (max(ts), *h2)
for part1 in (True, False):
h = sorted((hand(h,part1), int(b)) for h, b in (l.split() for l in lines))
t = 0
for i,(_,b) in enumerate(h):
t+=i*b+b
print('Part', 2-part1, ':', t)