AdventOfCode/2024/day10.exs

80 lines
2.1 KiB
Elixir

#!/usr/bin/env elixir
defmodule Day10 do
def part1({grid, zeros}) do
zeros
|> Enum.map(fn point -> point |> score(grid, 0) |> Enum.uniq() |> Enum.count() end)
|> Enum.sum()
end
def score(point, _grid, 9), do: [point]
def score({x, y}, grid, height) do
find_neighbours(x, y, height, grid)
|> Enum.flat_map(fn {point, _} -> score(point, grid, height + 1) end)
end
def find_neighbours(x, y, height, grid) do
next_height = height + 1
grid
|> Map.take([{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}])
|> Enum.filter(&match?({_, ^next_height}, &1))
end
def part2({grid, zeros}) do
zeros
|> Enum.map(fn point -> point |> score(grid, 0) |> Enum.count() end)
|> Enum.sum()
end
def input do
with [input_filename] <- System.argv(),
{:ok, input} <- File.read(input_filename) do
{grid, zeros, _, _, _} =
for <<char::binary-1 <- input>>, reduce: {%{}, [], 0, 0, 0} do
{grid, zeros, x, max_x, y} ->
case char do
"\n" -> {grid, zeros, 0, x, y + 1}
"0" -> {Map.put(grid, {x, y}, 0), [{x, y} | zeros], x + 1, max_x, y}
char -> {Map.put(grid, {x, y}, String.to_integer(char)), zeros, x + 1, max_x, y}
end
end
{grid, zeros}
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 day10.exs input_filename")
end
end
Day10.run()