AdventOfCode/2024/day6.exs

85 lines
2.3 KiB
Elixir
Raw Normal View History

2024-12-06 06:17:38 +00:00
#!/usr/bin/env elixir
defmodule Day6 do
def part1({max_x, max_y, {x, y}, obstacles}) do
walk(x, y, max_x, max_y, obstacles, MapSet.new(), 0, -1)
|> MapSet.size()
end
def walk(x, y, max_x, max_y, _obstacles, visited, _x_dir, _) when x == max_x or y == max_y do
visited
end
def walk(x, y, max_x, max_y, obstacles, visited, x_dir, y_dir) do
next_x = x + x_dir
next_y = y + y_dir
if MapSet.member?(obstacles, {next_x, next_y}) do
{x_dir, y_dir} = turn_right(x_dir, y_dir)
walk(x, y, max_x, max_y, obstacles, visited, x_dir, y_dir)
else
visited = MapSet.put(visited, {x, y})
walk(next_x, next_y, max_x, max_y, obstacles, visited, x_dir, y_dir)
end
end
def turn_right(0, -1), do: {1, 0}
def turn_right(1, 0), do: {0, 1}
def turn_right(0, 1), do: {-1, 0}
def turn_right(-1, 0), do: {0, -1}
def part2(_input) do
# hmmmmmmm probably need completely different solution
:ok
end
def input do
with [input_filename] <- System.argv(),
{:ok, input} <- File.read(input_filename) do
for <<char::binary-1 <- input>>, reduce: {0, 0, 0, nil, MapSet.new()} do
{x, max_x, y, guard, obstacles} ->
case char do
"." -> {x + 1, max_x, y, guard, obstacles}
"#" -> {x + 1, max_x, y, guard, MapSet.put(obstacles, {x, y})}
"^" -> {x + 1, max_x, y, {x, y}, obstacles}
"\n" -> {0, x, y + 1, guard, obstacles}
end
end
|> Tuple.delete_at(0)
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 day6.exs input_filename")
end
end
Day6.run()