#!/usr/bin/env elixir defmodule Patrol do defstruct obstacles: MapSet.new(), visited: MapSet.new(), path: MapSet.new(), x: 0, y: 0, max_x: nil, max_y: nil, dir_x: 0, dir_y: -1 end defmodule Day6 do def part1(patrol), do: MapSet.size(patrol(patrol).visited) def patrol(%Patrol{} = patrol) when patrol.x in [-1, patrol.max_x] or patrol.y in [-1, patrol.max_y] do patrol end def patrol(%Patrol{} = patrol) do next_x = patrol.x + patrol.dir_x next_y = patrol.y + patrol.dir_y patrol = if MapSet.member?(patrol.obstacles, {next_x, next_y}) do {dir_x, dir_y} = turn_right(patrol.dir_x, patrol.dir_y) %Patrol{patrol | dir_x: dir_x, dir_y: dir_y} else visited = MapSet.put(patrol.visited, {patrol.x, patrol.y}) %Patrol{patrol | x: next_x, y: next_y, visited: visited} end next_path = {patrol.x, patrol.y, patrol.dir_x, patrol.dir_y} if MapSet.member?(patrol.path, next_path) do :loop else patrol = %Patrol{patrol | path: MapSet.put(patrol.path, next_path)} patrol(patrol) 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(patrol) do completed_patrol = patrol(patrol) candidate_obstructions = Enum.reduce(completed_patrol.visited, MapSet.new(), fn {x, y}, candidate_obstructions -> Enum.into([{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}], candidate_obstructions) end) Enum.count(candidate_obstructions, fn {x, y} -> new_obstacles = MapSet.put(patrol.obstacles, {x, y}) new_patrol = %Patrol{patrol | obstacles: new_obstacles} patrol(new_patrol) == :loop end) 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 <>, 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} 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()