shritesh
Advent of Code 2023 - Day 7
I mapped both the cards and every possible hand to numeric values and sorted them. In part 2 I could only think of replacing the jokers with all unique values in the hand. There’s probably a better way.
Most Liked
seeplusplus
In part 2 I could only think of replacing the jokers with all unique values in the hand
Heh, better than I did, I just brute forced and tried every card possible
/shrug
pehbehbeh
bjorng
Today’s puzzle was fun!
My solution:
Aetherus
I accidentally removed my code, so I wrote it again and didn’t bother to refactor it.
Prep
{:ok, puzzle_input} =
KinoAOC.download_puzzle("2023", "7", System.fetch_env!("LB_AOC_SESSION"))
strengths =
?2..?9
|> Map.new(&{&1, &1 - ?0})
|> Map.merge(%{
?T => 10,
?J => 11,
?Q => 12,
?K => 13,
?A => 14
})
Part 1
puzzle_input
|> String.split()
|> Stream.chunk_every(2)
|> Stream.map(fn [hand, bid] ->
cards = String.to_charlist(hand)
freqs = cards |> Enum.frequencies() |> Map.values() |> Enum.sort(:desc)
scores = Enum.map(cards, &strengths[&1])
{freqs, scores, String.to_integer(bid)}
end)
|> Enum.sort()
|> Stream.map(&elem(&1, 2))
|> Stream.with_index(1)
|> Stream.map(fn {bid, rank} -> bid * rank end)
|> Enum.sum()
Part 2
strengths = %{strengths | ?J => 1}
puzzle_input
|> String.split()
|> Stream.chunk_every(2)
|> Stream.map(fn [hand, bid] ->
cards = String.to_charlist(hand)
freqs = cards |> Enum.frequencies()
{jokers, freqs} = Map.pop(freqs, ?J, 0)
freqs = freqs |> Map.values() |> Enum.sort(:desc)
freqs = (freqs == []) && [5] || [hd(freqs) + jokers | tl(freqs)]
scores = Enum.map(cards, &strengths[&1])
{freqs, scores, String.to_integer(bid)}
end)
|> Enum.sort()
|> Stream.map(&elem(&1, 2))
|> Stream.with_index(1)
|> Stream.map(fn {bid, rank} -> bid * rank end)
|> Enum.sum()
code-shoily
I loved doing this. The way I decided to calculate rank through pattern matching ended up being visual cue to compute the J assisted ranking.
advent_of_code/lib/2023/day_07.ex at master · code-shoily/advent_of_code (github.com)
This felt so natural!
One valuable lesson learned though.
My smaller? function had @card_rank_1 as default parameter. And it is recursive, so when I called it with @card_rank_2 during part 2, I forgot to provide the second parameter on the recursive calls, so subsequent matches were lies! And to make it worse, sample data were immune to this ranking algorithm and kept giving me right answer so I spent some time in frustration.








