Advent of Code 2023 - Day 7Camel Cards
| Problem statement | Source code | Tags: Data structuresPuzzle
Part 1
I have to complain: every day, my struggle starts with parsing the input π
Then, we can calculate the type of each hand. R's table() function is very handy: it generates a frequency table of the values. Then we just need to check the number of unique values and the maximum count. I define each type as an integer, so I can easily compare them later.
Then we can sort the hands by the type. Unfortunately, the ordering is relative and not absolute, so we need a comparator function. R's order() function can only sort by columns, so I wrote a quicksort() function that takes a custom comparator. Then we can sort the dataframe by row.
Finally calculating the total score is just a matter of multiplying the bid by the rank. sum(seq_len(nrow(data)) * data$bid)
Part 2
A useful observation is that there's a single choice for what jokers can become: the most frequent card. Because the max_count is the determining factor for the hand type (the more max_count is, the better the hand), we want to bump it up as much as possible. So we can just replace the jokers with the most frequent card in the hand.
(Note that length(card_counts) may be 0 if the hand is all jokers, but that's fine because the hand_type() function will just check max_count and return five of a kind in that case.)