AdventOfCode/2023/day7/p2_1.py

58 lines
1.3 KiB
Python
Raw Normal View History

2023-12-08 20:49:41 +01:00
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])
2023-12-08 22:11:03 +01:00
def value(card,p2):
return 'AKQJT98765432'.index(card) if not p2 else 'AKQT98765432J'.index(card)
2023-12-08 20:49:41 +01:00
2023-12-08 22:11:03 +01:00
def score(card,p2):
2023-12-08 20:49:41 +01:00
tmp = sorted(list(Counter(card).values()),reverse=True)
2023-12-08 22:11:03 +01:00
if p2 and (j := card.count('J')) and j < 5:
tmp.remove(j)
tmp[0] += j
tmp = sorted(tmp,reverse=True)
2023-12-08 20:49:41 +01:00
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
2023-12-08 22:11:03 +01:00
else:
print('ERROR')
2023-12-08 20:49:41 +01:00
2023-12-08 22:11:03 +01:00
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)
2023-12-08 20:49:41 +01:00
2023-12-08 22:11:03 +01:00
tmp = play(cards,False)
2023-12-08 20:49:41 +01:00
result = 0
2023-12-08 22:11:03 +01:00
for idx,i in enumerate(tmp):
result += cards[i[2]]*(idx+1)
print('Part 1: ' + str(result))
2023-12-08 20:49:41 +01:00
2023-12-08 22:11:03 +01:00
tmp = play(cards,True)
result = 0
2023-12-08 20:49:41 +01:00
for idx,i in enumerate(tmp):
result += cards[i[2]]*(idx+1)
2023-12-08 22:11:03 +01:00
print('Part 2: ' + str(result))