AdventOfCode/2024/day6.exs

93 lines
2.5 KiB
Elixir
Raw Normal View History

2024-12-06 06:17:38 +00:00
#!/usr/bin/env elixir
defmodule Patrol do
defstruct obstacles: MapSet.new(),
visited: MapSet.new(),
x: 0,
y: 0,
max_x: nil,
max_y: nil,
dir_x: 0,
dir_y: -1
end
2024-12-06 06:17:38 +00:00
defmodule Day6 do
def part1(%Patrol{} = patrol) when patrol.x == patrol.max_x or patrol.y == patrol.max_y do
MapSet.size(patrol.visited)
2024-12-06 06:17:38 +00:00
end
def part1(%Patrol{} = patrol) do
next_x = patrol.x + patrol.dir_x
next_y = patrol.y + patrol.dir_y
2024-12-06 06:17:38 +00:00
if MapSet.member?(patrol.obstacles, {next_x, next_y}) do
{dir_x, dir_y} = turn_right(patrol.dir_x, patrol.dir_y)
part1(%Patrol{patrol | dir_x: dir_x, dir_y: dir_y})
2024-12-06 06:17:38 +00:00
else
visited = MapSet.put(patrol.visited, {patrol.x, patrol.y})
part1(%Patrol{patrol | x: next_x, y: next_y, visited: visited})
2024-12-06 06:17:38 +00:00
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
{_x, max_x, max_y, {x, y}, obstacles} =
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
%Patrol{x: x, y: y, max_x: max_x, max_y: max_y, obstacles: obstacles}
2024-12-06 06:17:38 +00:00
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()