From 7589011fa658ca74ccf154c84344a1d8178cb7ff Mon Sep 17 00:00:00 2001 From: Adam Millerchip Date: Fri, 6 Dec 2024 15:17:38 +0900 Subject: [PATCH] 2024 Day6 part 1 --- 2024/day6.exs | 84 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100755 2024/day6.exs diff --git a/2024/day6.exs b/2024/day6.exs new file mode 100755 index 0000000..8008426 --- /dev/null +++ b/2024/day6.exs @@ -0,0 +1,84 @@ +#!/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 <>, 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()