# Advent of Code - 2023

This is a solution to Day 7 of Advent of Code 2023.

# Day 7: Camel Cards

Your all-expenses-paid trip turns out to be a one-way, five-minute ride in an airship. (At least it's a cool airship!) It drops you off at the edge of a vast desert and descends back to Island Island.

"Did you bring the parts?"

You turn around to see an Elf completely covered in white clothing, wearing goggles, and riding a large camel.

"Did you bring the parts?" she asks again, louder this time. You aren't sure what parts she's looking for; you're here to figure out why the sand stopped.

"The parts! For the sand, yes! Come with me; I will show you." She beckons you onto the camel.

After riding a bit across the sands of Desert Island, you can see what look like very large rocks covering half of the horizon. The Elf explains that the rocks are all along the part of Desert Island that is directly above Island Island, making it hard to even get there. Normally, they use big machines to move the rocks and filter the sand, but the machines have broken down because Desert Island recently stopped receiving the parts they need to fix the machines.

You've already assumed it'll be your job to figure out why the parts stopped when she asks if you can help. You agree automatically.

Because the journey will take a few days, she offers to teach you the game of Camel Cards. Camel Cards is sort of similar to poker except it's designed to be easier to play while riding a camel.

In Camel Cards, you get a list of hands, and your goal is to order them based on the strength of each hand. A hand consists of five cards labeled one of A, K, Q, J, T, 9, 8, 7, 6, 5, 4, 3, or 2. The relative strength of each card follows this order, where A is the highest and 2 is the lowest.

Every hand is exactly one type. From strongest to weakest, they are:

- Five of a kind, where all five cards have the same label: AAAAA
- Four of a kind, where four cards have the same label and one card has a different label: AA8AA
- Full house, where three cards have the same label, and the remaining two cards share a different label: 23332
- Three of a kind, where three cards have the same label, and the remaining two cards are each different from any other card in the hand: TTT98
- Two pair, where two cards share one label, two other cards share a second label, and the remaining card has a third label: 23432
- One pair, where two cards share one label, and the other three cards have a different label from the pair and each other: A23A4
- High card, where all cards' labels are distinct: 23456
Hands are primarily ordered based on type; for example, every full house is stronger than any three of a kind.

If two hands have the same type, a second ordering rule takes effect. Start by comparing the first card in each hand. If these cards are different, the hand with the stronger first card is considered stronger. If the first card in each hand have the same label, however, then move on to considering the second card in each hand. If they differ, the hand with the higher second card wins; otherwise, continue with the third card in each hand, then the fourth, then the fifth.

So, 33332 and 2AAAA are both four of a kind hands, but 33332 is stronger because its first card is stronger. Similarly, 77888 and 77788 are both a full house, but 77888 is stronger because its third card is stronger (and both hands have the same first and second card).

To play Camel Cards, you are given a list of hands and their corresponding bid (your puzzle input). For example:

`32T3K 765 T55J5 684 KK677 28 KTJJT 220 QQQJA 483`

This example shows five hands; each hand is followed by its bid amount. Each hand wins an amount equal to its bid multiplied by its rank, where the weakest hand gets rank 1, the second-weakest hand gets rank 2, and so on up to the strongest hand. Because there are five hands in this example, the strongest hand will have rank 5 and its bid will be multiplied by 5.

So, the first step is to put the hands in order of strength:

- 32T3K is the only one pair and the other hands are all a stronger type, so it gets rank 1.
- KK677 and KTJJT are both two pair. Their first cards both have the same label, but the second card of KK677 is stronger (K vs T), so KTJJT gets rank 2 and KK677 gets rank 3.
- T55J5 and QQQJA are both three of a kind. QQQJA has a stronger first card, so it gets rank 5 and T55J5 gets rank 4.
Now, you can determine the total winnings of this set of hands by adding up the result of multiplying each hand's bid with its rank (765 _ 1 + 220 _ 2 + 28 _ 3 + 684 _ 4 + 483 * 5). So the total winnings in this example are 6440.

Find the rank of every hand in your set. What are the total winnings?

## Modeling!

I've built my fair share of different card game models for programming courses and puzzles like these so I knew I wanna make the hand of cards into a class that knows its own value and can be sorted with other Hands.

I first build an Enum for the values of different hands. This way, we can deal with named hands and only refer to their ranking when needed for sorting. Better hand, higher value.

Next, I created a dictionary to map characters into their numeric values. This is also used for sorting only.

```
from enum import Enum
class HandValue(Enum):
HIGH_CARD = 1
ONE_PAIR = 2
TWO_PAIRS = 3
THREE_OF_A_KIND = 4
FULL_HOUSE = 5
FOUR_OF_A_KIND = 6
FIVE_OF_A_KIND = 7
NUMERIC_VALUES = {
'2': 2,
'3': 3,
'4': 4,
'5': 5,
'6': 6,
'7': 7,
'8': 8,
'9': 9,
'T': 10,
'J': 11,
'Q': 12,
'K': 13,
'A': 14
}
```

For the `Hand`

class, I store the cards themselves, a set of them and a card count Counter.

I then built a function for each hand type (except the `HIGH_CARD`

which is default if nothing else is met.

To get the value of a hand, I go down from the best hand to worst, and check until a match is found.

To compare two hands, they are either sorted by their full hand value and if that is the same, card by card by their numeric value.

```
from collections import Counter
class Hand:
def __init__(self, cards):
self.cards = list(cards)
self.card_set = set(cards)
self.card_counts = Counter(cards)
self.value = self.get_value()
self.numeric_values = NUMERIC_VALUES
def is_five_of_a_kind(self):
return len(self.card_set) == 1
def is_four_of_a_kind(self):
if len(self.card_set) != 2:
return False
return any(c for c in self.card_counts.values() if c == 4)
def is_full_house(self):
has_triplet = any(c for c in self.card_counts.values() if c == 3)
has_pair = any(c for c in self.card_counts.values() if c == 2)
return has_triplet and has_pair
def is_three_of_a_kind(self):
return any(c for c in self.card_counts.values() if c == 3)
def is_two_pairs(self):
pairs = [c for c in self.card_counts.values() if c == 2]
return len(pairs) == 2
def is_one_pair(self):
pairs = [c for c in self.card_counts.values() if c == 2]
return len(pairs) == 1
def get_value(self):
if self.is_five_of_a_kind():
return HandValue.FIVE_OF_A_KIND
if self.is_four_of_a_kind():
return HandValue.FOUR_OF_A_KIND
if self.is_full_house():
return HandValue.FULL_HOUSE
if self.is_three_of_a_kind():
return HandValue.THREE_OF_A_KIND
if self.is_two_pairs():
return HandValue.TWO_PAIRS
if self.is_one_pair():
return HandValue.ONE_PAIR
return HandValue.HIGH_CARD
def __lt__(self, other):
if self.value.value != other.value.value:
return self.value.value < other.value.value
else:
for c1, c2 in zip(self.cards, other.cards):
c1_value = self.numeric_values[c1]
c2_value = self.numeric_values[c2]
if c1_value == c2_value:
continue
return c1_value < c2_value
def __repr__(self):
return f'<Hand: {"".join(self.cards)} {self.value}>'
```

## Read input

Today's input is simple. Each line has the cards and the bid separated by space. I convert the cards to a `Hand`

and bid to an `int`

.

```
from utils import read_input
def transformer(line):
hand, bid = line.split(' ')
hand = Hand(hand)
bid = int(bid)
return hand, bid
hands = read_input(7, transformer)
```

To solve the first part, I loop over all the hands in sorted order and multiply their rank with their bid.

```
part_1 = 0
for i, (hand, bid) in enumerate(sorted(hands)):
part_1 += (i+1) * bid
print(part_1)
assert part_1 == 253205868
```

## Part 2

To make things a little more interesting, the Elf introduces one additional rule. Now, J cards are jokers - wildcards that can act like whatever card would make the hand the strongest type possible.

To balance this, J cards are now the weakest individual cards, weaker even than 2. The other cards stay in the same order: A, K, Q, T, 9, 8, 7, 6, 5, 4, 3, 2, J.

J cards can pretend to be whatever card is best for the purpose of determining hand type; for example, QJJQ2 is now considered four of a kind. However, for the purpose of breaking ties between two hands of the same type, J is always treated as J, not the card it's pretending to be: JKKK2 is weaker than QQQQ2 because J is weaker than Q.

Now, the above example goes very differently:

`32T3K 765 T55J5 684 KK677 28 KTJJT 220 QQQJA 483`

- 32T3K is still the only one pair; it doesn't contain any jokers, so its strength doesn't increase.
- KK677 is now the only two pair, making it the second-weakest hand.
- T55J5, KTJJT, and QQQJA are now all four of a kind! T55J5 gets rank 3, QQQJA gets rank 4, and KTJJT gets rank 5.
With the new joker rule, the total winnings in this example are 5905.

Using the new joker rule, find the rank of every hand in your set. What are the new total winnings>?

For this second part, the only changes needed to make are in the modeling.

First, we drop the value of 'J' cards to zero for sorting.

Second, thanks to inheritance, we only need to rewrite the methods that are changed by the addition of Joker cards. Notably, two pairs does not change because it can never happen with a Joker as that Joker would turn it into a three of a kind.

Setting up, finding hand value and making comparisons all remain mostly unaffected. We add a `self.joker`

attribute for the Joker hand and use `JOKER_NUMERIC_VALUES`

for comparison instead of `NUMERIC_VALUES`

.

```
from collections import Counter
JOKER_NUMERIC_VALUES = NUMERIC_VALUES.copy()
JOKER_NUMERIC_VALUES['J'] = 0
class JokerHand(Hand):
def __init__(self, cards):
self.joker = 'J' in cards
super().__init__(cards)
self.numeric_values = JOKER_NUMERIC_VALUES
def is_five_of_a_kind(self):
if not self.joker:
return super().is_five_of_a_kind()
return len(self.card_set) <= 2
def is_four_of_a_kind(self):
if not self.joker:
return super().is_four_of_a_kind()
return any(count for card, count in self.card_counts.items() if count == 4 - self.cards.count('J') and card != 'J')
def is_full_house(self):
has_triplet = any(c for c in self.card_counts.values() if c == 3)
has_pair = any(c for c in self.card_counts.values() if c == 2)
full_house = has_triplet and has_pair
if full_house:
return True
elif not full_house and not self.joker:
return False
else: # Not a natural full house but has joker so it might still be
pairs = [card for card, count in self.card_counts.items() if count == 2]
return len(pairs) == 2
def is_three_of_a_kind(self):
return any(c for c in self.card_counts.values() if c == 3 - self.cards.count('J'))
def is_one_pair(self):
if self.joker:
return True
return super().is_one_pair()
```

When reading input, we convert hands into `JokerHand`

s instead and otherwise it's the same.

```
def transformer(line):
hand, bid = line.split(' ')
hand = JokerHand(hand)
bid = int(bid)
return hand, bid
jokerhands = read_input(7, transformer)
```

The actual solution is exactly the same at this point than part 1.

```
part_2 = 0
for i, (hand, bid) in enumerate(sorted(jokerhands)):
part_2 += (i+1) * bid
print(part_2)
assert part_2 == 253907829
```

## Two stars!

7 days, 14 stars. Woohoo! 36 to go.