From bc471d90a38b3abd6928ae6dd13e381acbec4efb Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Wed, 11 Dec 2024 14:57:36 +0900 Subject: [PATCH] 2024 Day 11 part 1 (and naive slow part 2, come back to it...) --- 2024/day11.exs | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2024/day11.exs diff --git a/2024/day11.exs b/2024/day11.exs new file mode 100644 index 0000000..261069e --- /dev/null +++ b/2024/day11.exs @@ -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()