summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorTomasz Kramkowski <tomasz@kramkow.ski>2023-12-07 14:44:55 +0000
committerTomasz Kramkowski <tomasz@kramkow.ski>2023-12-07 14:44:55 +0000
commit7fc0dafedaeaf4cd7dbb285374fcef7953565f77 (patch)
tree6a39fee5f4e7d7dd66e3ae8040c3eca946696803
parenteb5190b7d348df23dfa848a5cdbfead3cbfc38ce (diff)
downloadaoc2023-7fc0dafedaeaf4cd7dbb285374fcef7953565f77.tar.gz
aoc2023-7fc0dafedaeaf4cd7dbb285374fcef7953565f77.tar.xz
aoc2023-7fc0dafedaeaf4cd7dbb285374fcef7953565f77.zip
day 7
-rw-r--r--7.py77
1 files changed, 77 insertions, 0 deletions
diff --git a/7.py b/7.py
new file mode 100644
index 0000000..914cb30
--- /dev/null
+++ b/7.py
@@ -0,0 +1,77 @@
+from collections import Counter
+from sys import stdin
+from typing import TypeAlias
+
+Hand: TypeAlias = tuple[int, int, int, int, int]
+
+inp = [(l[0], int(l[1])) for l in (l.rstrip().split() for l in stdin)]
+
+
+def parse_hand(card_worth: dict[str, int], hand: str) -> Hand:
+ ret = tuple(card_worth[c] for c in hand)
+ if len(ret) != 5:
+ raise ValueError
+ return ret
+
+
+def hand_type(c: list[tuple[int, int]]) -> int:
+ if c[0][1] == 5:
+ return 6
+ if c[0][1] == 4:
+ return 5
+ if c[0][1] == 3 and c[1][1] == 2:
+ return 4
+ if c[0][1] == 3:
+ return 3
+ if c[0][1] == 2 and c[1][1] == 2:
+ return 2
+ if c[0][1] == 2:
+ return 1
+ return 0
+
+
+def p1(inp: list[tuple[str, int]]):
+ cards = "AKQJT98765432"
+ card_worth = {c: i for i, c in enumerate(reversed(cards))}
+
+ def _hand_type(hand: Hand) -> int:
+ return hand_type(Counter(hand).most_common())
+
+ return sum(
+ (i + 1) * h[1]
+ for i, h in enumerate(
+ sorted(
+ ((parse_hand(card_worth, i[0]), i[1]) for i in inp),
+ key=lambda i: (_hand_type(i[0]), *i[0]),
+ )
+ )
+ )
+
+
+def p2(inp: list[tuple[str, int]]):
+ cards = "AKQT98765432J"
+ card_worth = {c: i for i, c in enumerate(reversed(cards))}
+
+ def _hand_type(hand: Hand) -> int:
+ c = Counter(hand)
+ mc = c.most_common()
+ if 0 in c and len(mc) != 1:
+ target = next(e[0] for e in mc if e[0] != 0)
+ c[target] += c[0]
+ c[0] = 0
+ mc = c.most_common()
+ return hand_type(mc)
+
+ return sum(
+ (i + 1) * h[1]
+ for i, h in enumerate(
+ sorted(
+ ((parse_hand(card_worth, i[0]), i[1]) for i in inp),
+ key=lambda i: (_hand_type(i[0]), *i[0]),
+ ),
+ )
+ )
+
+
+print(p1(inp))
+print(p2(inp))