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 part2(stones) do
def blink([0 | rest]), do: [1 | blink(rest)] blink(stones, 75)
end
def blink([stone | rest]) do 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) string = Integer.to_string(stone)
size = byte_size(string) size = byte_size(string)
if rem(size, 2) == 0 do if rem(size, 2) == 0 do
string {a, b} = String.split_at(string, div(size, 2))
|> 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? next
def part2(stones) do |> Map.update(String.to_integer(a), count, &(&1 + count))
1..75 |> Map.update(String.to_integer(b), count, &(&1 + count))
|> Enum.reduce(stones, fn _, stones -> blink(stones) end) else
|> Enum.count() 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