AdventOfCode/2023/day7/p2_1.py

58 lines
1.3 KiB
Python

import sys
from pprint import pp
from collections import Counter
input_f = sys.argv[1]
cards = {}
with open(input_f) as file:
for line in file:
tmp = line.split()
cards[tmp[0]] = int(tmp[1])
def value(card,p2):
return 'AKQJT98765432'.index(card) if not p2 else 'AKQT98765432J'.index(card)
def score(card,p2):
tmp = sorted(list(Counter(card).values()),reverse=True)
if p2 and (j := card.count('J')) and j < 5:
tmp.remove(j)
tmp[0] += j
tmp = sorted(tmp,reverse=True)
if tmp == [5]:
return 1
elif tmp == [4,1]:
return 2
elif tmp == [3,2]:
return 3
elif tmp == [3,1,1]:
return 4
elif tmp == [2,2,1]:
return 5
elif tmp == [2,1,1,1]:
return 6
elif tmp == [1,1,1,1,1]:
return 7
else:
print('ERROR')
def play(cards,p2):
scores = []
tmp = []
for i in cards:
tmp.append(tuple((score(i,p2),tuple(value(c,p2) for c in i),i)))
return sorted(tmp, key=lambda x: (x[0], x[1]),reverse=True)
tmp = play(cards,False)
result = 0
for idx,i in enumerate(tmp):
result += cards[i[2]]*(idx+1)
print('Part 1: ' + str(result))
tmp = play(cards,True)
result = 0
for idx,i in enumerate(tmp):
result += cards[i[2]]*(idx+1)
print('Part 2: ' + str(result))