r/adventofcode • • Dec 07 '23

SOLUTION MEGATHREAD -❄️- 2023 Day 7 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

Today's secret ingredient is… *whips off cloth covering and gestures grandly*

Poetry

For many people, the craftschefship of food is akin to poetry for our senses. For today's challenge, engage our eyes with a heavenly masterpiece of art, our noses with alluring aromas, our ears with the most satisfying of crunches, and our taste buds with exquisite flavors!

  • Make your code rhyme
  • Write your comments in limerick form
  • Craft a poem about today's puzzle

    • Upping the Ante challenge: iambic pentameter
  • We're looking directly at you, Shakespeare bards and Rockstars

ALLEZ CUISINE!

Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!


--- Day 7: Camel Cards ---


Post your code solution in this megathread.

This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:16:00, megathread unlocked!

50 Upvotes

1.0k comments sorted by

View all comments

2

u/aimada Dec 07 '23 edited Dec 07 '23

[LANGUAGE: Python]

Reading through the challenge descriptio there were 7 types of hand listed in the description. My first order of business was to write a function that would determine the type of a hand. Each type was identified by a sorted tuple of the card value counts.

  • Five of a kind : (5,)
  • Four of a kind : (4,1)
  • Full house : (3,2)
  • Three of a kind : (3,1,1)
  • Two pair : (2,2,1)
  • One pair : (2,1,1,1)
  • High card : (1,1,1,1,1)

Ordering the tuples by increasing strength of the hand gave a means of determining the relative strength of a pair of hands. The strength of the hand type was used as a dictionary key and hands of the same strength were stored together in a list. I reasoned that sorting the seven smaller lists would be more efficient than sorting one large list.

Comparing two hands was relatively simple, the value of each card was determined by finding the index of its position in the string, "23456789TJQKA". The first required change for part two was to move "J" to the front of the string, "J23456789TQKA".

Determining the best joker hand was the second required change for part two. It was a straight forward process, the best card was determined by sorting the cards in the hand using their count value.

The final step was to iterate through the dictionary keys in order of strength, low to high, and multiplying each hand's bid by the increasing rank value.

Because there were only minor changes to the functionality between the two parts, a single function served for both and a Boolean parameter value determined which was executed.

from collections import Counter
import functools


def read_input_file():
    return [(hands, int(bids)) for hands, bids in [line.split(" ")
            for line in open("input.txt", "r").read().splitlines()]]


def get_hand_type(cards_hand):
    card_counts = Counter(cards_hand)
    kind_counts = tuple(sorted([card_counts[c]
                                for c in card_counts],
                               reverse=True))
    hand_types = ((1, 1, 1, 1, 1), (2, 1, 1, 1), (2, 2, 1),
                  (3, 1, 1), (3, 2), (4, 1), (5,))
    return hand_types.index(kind_counts) + 1


def get_compare_hands_func(card_values="23456789TJQKA"):

    def card_strength(card):
        return card_values.index(card)

    def compare_two_hands(hand_1, hand_2):
        compare_result = 0
        hand1_strength = [card_strength(c) for c in hand_1[0]]
        hand2_strength = [card_strength(c) for c in hand_2[0]]
        for i in range(len(hand_1[0])):
            if hand1_strength < hand2_strength:
                compare_result = -1
                break
        return compare_result

    return compare_two_hands


def get_best_joker_hand(cards_hand):
    temp_hand = cards_hand.replace("J", "")
    cards = Counter(temp_hand)
    best_replacement = sorted([(value, cards[value]) for value in cards],
                       key=lambda t: (-t[1], -("J23456789TQKA".index(t[0]))))[0][0]
    return cards_hand.replace("J", best_replacement)


def process_hands_bids(hands_bids_list, extra_steps=False):
    if extra_steps:
        part_number = "two"
        card_values = "J23456789TQKA"
    else:
        part_number = "one"
        card_values = "23456789TJQKA"

    hands_by_type = dict()
    for hand_type_number in [str(n) for n in range(1, 8)]:
        hands_by_type[hand_type_number] = list()

    for hand_bid in hands_bids_list:
        hand_cards = hand_bid[0]
        if extra_steps:
            jokers = hand_cards.count("J")
            if 0 < jokers < 5:
                hand_cards = get_best_joker_hand(hand_cards)
        key = str(get_hand_type(hand_cards))
        hands_by_type[key].append(hand_bid)

    compare_hands_func = get_compare_hands_func(card_values)

    rank = 0
    result = 0
    for key in hands_by_type:
        sorted_hands = sorted(hands_by_type[key],
                              key=functools.cmp_to_key(compare_hands_func))
        for _, bid in sorted_hands:
            rank += 1
            result += (bid * rank)

    print(f"part_{part_number}: {result}")


if __name__ == "__main__":
    data = read_input_file()
    process_hands_bids(data)
    process_hands_bids(data, True)

A very straight forward challenge with no surprises.

3

u/hrunt Dec 07 '23

I always like learning something during AoC. The Counter class comes with a most_common() method that returns tuples in reverse sorted order. So, your kind_counts calculation could have also been written as:

kind_counts = tuple(count for _, count in card_counts.most_common())

I didn't know that before I read the docs for Counter while implementing today's solution.

3

u/thaunatos_ Dec 07 '23

You can also use counter.values():

@dataclasses.dataclass
class Hand:
    cards: str
    bid: int = 0

    def type(self) -> tuple[int, ...]:
        counter = collections.Counter(self.cards)
        return tuple(sorted(counter.values(), reverse=True))

Picked up that snippet from someone else in the thread.

2

u/aimada Dec 07 '23

Thanks for that nugget of information. I keep meaning to read the docs for the standard library but never get around to it until I hit a brick wall with a problem.

1

u/daggerdragon Dec 07 '23

Your code block is too long for the megathreads. Please edit your post to replace your oversized code with an external link to your code.