From 21a79d76db17a3f9ca3fd8a4082a50ff0dcdcb63 Mon Sep 17 00:00:00 2001 From: Daniel Lin Date: Thu, 7 Dec 2023 02:32:10 -0500 Subject: [PATCH] Day 7: Camel Cards --- README.md | 2 +- py/aoc2023/day7.py | 62 ++++++++++++++++++++++++++++++++++++++++++++++ py/pyproject.toml | 1 + 3 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 py/aoc2023/day7.py diff --git a/README.md b/README.md index 26a493f5..060f86b2 100644 --- a/README.md +++ b/README.md @@ -11,4 +11,4 @@ Development occurs in language-specific directories: |[Day4.hs](hs/src/Day4.hs)|[Day4.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day4.kt)|[day4.py](py/aoc2023/day4.py)|[day4.rs](rs/src/day4.rs)| |[Day5.hs](hs/src/Day5.hs)|[Day5.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day5.kt)|[day5.py](py/aoc2023/day5.py)|[day5.rs](rs/src/day5.rs)| |[Day6.hs](hs/src/Day6.hs)|[Day6.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day6.kt)|[day6.py](py/aoc2023/day6.py)|[day6.rs](rs/src/day6.rs)| -|[Day7.hs](hs/src/Day7.hs)|[Day7.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day7.kt)||| +|[Day7.hs](hs/src/Day7.hs)|[Day7.kt](kt/aoc2023-lib/src/commonMain/kotlin/com/github/ephemient/aoc2023/Day7.kt)|[day7.py](py/aoc2023/day7.py)|| diff --git a/py/aoc2023/day7.py b/py/aoc2023/day7.py new file mode 100644 index 00000000..600bff0c --- /dev/null +++ b/py/aoc2023/day7.py @@ -0,0 +1,62 @@ +""" +Day 7: Camel Cards +""" + +from collections import Counter + +SAMPLE_INPUT = """ +32T3K 765 +T55J5 684 +KK677 28 +KTJJT 220 +QQQJA 483 +""" + + +def _rank(hand: tuple[int]): + counts = Counter(x for x in hand if x >= 0).most_common(2) + count0 = counts[0][1] if counts else 0 + count1 = counts[1][1] if len(counts) > 1 else 0 + jokers = sum(x < 0 for x in hand) + # pylint: disable=too-many-return-statements + if count0 + jokers >= 5: + return 6 + if count0 + jokers >= 4: + return 5 + if count0 + count1 + jokers >= 5: + return 4 + if count0 + jokers >= 3: + return 3 + if count0 + count1 + jokers >= 4: + return 2 + if count0 + jokers >= 2: + return 1 + return 0 + + +def _solve(cards: str, data: str): + hands = [ + (_rank(hand := tuple(map(cards.find, words[0]))), hand, int(words[1])) + for line in data.splitlines() + if len(words := line.split(maxsplit=1)) == 2 + ] + return sum((i + 1) * bid for i, (_, _, bid) in enumerate(sorted(hands))) + + +def part1(data): + """ + >>> part1(SAMPLE_INPUT) + 6440 + """ + return _solve("23456789TJQKA", data) + + +def part2(data): + """ + >>> part2(SAMPLE_INPUT) + 5905 + """ + return _solve("23456789TQKA", data) + + +parts = (part1, part2) diff --git a/py/pyproject.toml b/py/pyproject.toml index 04b1ef3b..d99ca4de 100644 --- a/py/pyproject.toml +++ b/py/pyproject.toml @@ -28,6 +28,7 @@ day3 = "aoc2023.day3:parts" day4 = "aoc2023.day4:parts" day5 = "aoc2023.day5:parts" day6 = "aoc2023.day6:parts" +day7 = "aoc2023.day7:parts" [tool.black] target_version = ["py312"]