2024 Day 11 part 1 (and naive slow part 2, come back to it...)

This commit is contained in:
Adam Millerchip 2024-12-11 14:57:36 +09:00
parent df718ad579
commit bc471d90a3

76
2024/day11.exs Normal file
View file

@ -0,0 +1,76 @@
#!/usr/bin/env elixir
defmodule Day11 do
def part1(stones) do
1..25
|> Enum.reduce(stones, fn _, stones -> blink(stones) end)
|> Enum.count()
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
1..75
|> Enum.reduce(stones, fn _, stones -> blink(stones) end)
|> Enum.count()
end
def input do
with [input_filename] <- System.argv(),
{:ok, input} <- File.read(input_filename) do
input
|> String.split([" ", "\n"], trim: true)
|> Enum.map(&String.to_integer/1)
else
_ -> :error
end
end
#######################
# HERE BE BOILERPLATE #
#######################
def run do
case input() do
:error -> print_usage()
input -> run_parts_with_timer(input)
end
end
defp run_parts_with_timer(input) do
run_with_timer(1, fn -> part1(input) end)
run_with_timer(2, fn -> part2(input) end)
end
defp run_with_timer(part, fun) do
{time, result} = :timer.tc(fun)
IO.puts("Part #{part} (completed in #{format_time(time)}):\n")
IO.puts("#{inspect(result)}\n")
end
defp format_time(μsec) when μsec < 1_000, do: "#{μsec}μs"
defp format_time(μsec) when μsec < 1_000_000, do: "#{μsec / 1000}ms"
defp format_time(μsec), do: "#{μsec / 1_000_000}s"
defp print_usage do
IO.puts("Usage: elixir day11.exs input_filename")
end
end
Day11.run()