AdventOfCode/2024/day10.exs

79 lines
2.1 KiB
Elixir
Raw Permalink Normal View History

2024-12-10 07:30:33 +00:00
#!/usr/bin/env elixir
defmodule Day10 do
def part1({grid, zeros}) do
zeros
2024-12-10 08:16:54 +00:00
|> Enum.map(fn point -> point |> find_trails(grid, 0) |> Enum.uniq() |> Enum.count() end)
2024-12-10 07:30:33 +00:00
|> Enum.sum()
end
2024-12-10 08:16:54 +00:00
def find_trails(point, _grid, 9), do: [point]
2024-12-10 07:30:33 +00:00
2024-12-10 08:16:54 +00:00
def find_trails({x, y}, grid, height) do
2024-12-10 14:34:24 +00:00
find_neighbours(x, y, height + 1, grid)
2024-12-10 08:16:54 +00:00
|> Enum.flat_map(fn {point, _} -> find_trails(point, grid, height + 1) end)
2024-12-10 07:30:33 +00:00
end
def find_neighbours(x, y, height, grid) do
grid
|> Map.take([{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}])
2024-12-10 14:34:24 +00:00
|> Enum.filter(&match?({_, ^height}, &1))
2024-12-10 07:30:33 +00:00
end
def part2({grid, zeros}) do
zeros
2024-12-10 08:16:54 +00:00
|> Enum.map(fn point -> point |> find_trails(grid, 0) |> Enum.count() end)
2024-12-10 07:30:33 +00:00
|> 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} do
{grid, zeros, x, y} ->
2024-12-10 07:30:33 +00:00
case char do
"\n" -> {grid, zeros, 0, y + 1}
"0" -> {Map.put(grid, {x, y}, 0), [{x, y} | zeros], x + 1, y}
char -> {Map.put(grid, {x, y}, String.to_integer(char)), zeros, x + 1, y}
2024-12-10 07:30:33 +00:00
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()