2024 Day 11 Part 2 + retroactively use for Part 1

This commit is contained in:
Adam Millerchip 2024-12-11 22:29:10 +09:00
parent bc471d90a3
commit 26731083a3

View file

@ -1,34 +1,36 @@
#!/usr/bin/env elixir #!/usr/bin/env elixir
defmodule Day11 do defmodule Day11 do
def part1(stones) do def part1(stones) do
1..25 blink(stones, 25)
|> Enum.reduce(stones, fn _, stones -> blink(stones) end)
|> Enum.count()
end end
def blink([]), do: []
def blink([0 | rest]), do: [1 | blink(rest)]
def blink([stone | rest]) do
string = Integer.to_string(stone)
size = byte_size(string)
if rem(size, 2) == 0 do
string
|> String.split_at(div(size, 2))
|> Tuple.to_list()
|> Enum.map(&String.to_integer/1)
|> Kernel.++(blink(rest))
else
[stone |> Kernel.*(2024) | blink(rest)]
end
end
# probably have to track the changes rather than keep the whole list?
def part2(stones) do def part2(stones) do
1..75 blink(stones, 75)
|> Enum.reduce(stones, fn _, stones -> blink(stones) end) end
|> Enum.count()
def blink(stones, 0), do: stones |> Map.values() |> Enum.sum()
def blink(stones, times) do
stones
|> Enum.reduce(%{}, fn
{0, count}, next ->
Map.update(next, 1, count, &(&1 + count))
{stone, count}, next ->
string = Integer.to_string(stone)
size = byte_size(string)
if rem(size, 2) == 0 do
{a, b} = String.split_at(string, div(size, 2))
next
|> Map.update(String.to_integer(a), count, &(&1 + count))
|> Map.update(String.to_integer(b), count, &(&1 + count))
else
Map.update(next, stone * 2024, count, &(&1 + count))
end
end)
|> blink(times - 1)
end end
def input do def input do
@ -37,6 +39,7 @@ defmodule Day11 do
input input
|> String.split([" ", "\n"], trim: true) |> String.split([" ", "\n"], trim: true)
|> Enum.map(&String.to_integer/1) |> Enum.map(&String.to_integer/1)
|> Enum.frequencies()
else else
_ -> :error _ -> :error
end end