Improvements to day 7

This commit is contained in:
bluepython508
2023-12-07 12:12:31 +00:00
parent 863e1a5cb0
commit c500a9a280

View File

@@ -1,28 +1,14 @@
defmodule Aoc2023.Day7 do defmodule Aoc2023.Day7 do
use Aoc2023 use Aoc2023
@ranking_1 %{
?A => 13,
?K => 12,
?Q => 11,
?J => 10,
?T => 9,
?9 => 8,
?8 => 7,
?7 => 6,
?6 => 5,
?5 => 4,
?4 => 3,
?3 => 2,
?2 => 1
}
@ranking_2 @ranking_1 |> Map.put(?J, 0)
def hand_type(values) do def hand_type(values) do
for ty <- values, reduce: %{} do values
m -> Map.update(m, ty, 1, &(&1 + 1)) |> Enum.frequencies()
end |> then(fn freq ->
{jokers, freq_} = freq |> Map.pop(0, 0)
common = freq_ |> Enum.max_by(pipe(elem(1))) |> elem(0)
freq_ |> Map.update!(common, &(&1 + jokers))
end)
|> Enum.map(pipe(elem(1))) |> Enum.map(pipe(elem(1)))
|> Enum.sort(:desc) |> Enum.sort(:desc)
|> case do |> case do
@@ -37,7 +23,7 @@ defmodule Aoc2023.Day7 do
end end
def parse(input) do def parse(input) do
fn rankings, hand_rank -> fn rankings ->
input input
|> lines |> lines
|> Enum.map(&String.split/1) |> Enum.map(&String.split/1)
@@ -47,27 +33,34 @@ defmodule Aoc2023.Day7 do
bid |> String.to_integer() bid |> String.to_integer()
} }
end) end)
|> Enum.sort_by(elem(0) |> hand_rank.() &&& elem(0), :asc) |> Enum.sort_by(elem(0) |> hand_type &&& elem(0), :asc)
|> Enum.with_index(1) |> Enum.with_index(1)
|> Enum.map(fn {{_, bid}, index} -> bid * index end) |> Enum.map(fn {{_, bid}, index} -> bid * index end)
|> Enum.sum() |> Enum.sum()
end end
end end
@ranking [
?2,
?3,
?4,
?5,
?6,
?7,
?8,
?9,
?T,
?J,
?Q,
?K,
?A,
] |> Enum.with_index(1) |> Map.new
def part1(input) do def part1(input) do
input.(@ranking_1, &hand_type/1) input.(@ranking)
end end
def part2(input) do def part2(input) do
input.( input.(@ranking |> Map.put(?J, 0))
@ranking_2,
fn hand ->
@ranking_2
|> Enum.map(pipe(elem(1)))
|> Enum.map(fn j -> hand |> Enum.map(&if &1 == 0, do: j, else: &1) end)
|> Enum.map(&hand_type/1)
|> Enum.max()
end
)
end end
end end