Skip to content

Instantly share code, notes, and snippets.

@EricDykstra
Created December 1, 2016 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EricDykstra/41b46c9a40bf499f97252a81ef32dd8a to your computer and use it in GitHub Desktop.
Save EricDykstra/41b46c9a40bf499f97252a81ef32dd8a to your computer and use it in GitHub Desktop.
defmodule Day1 do
def main(file_path) do
file_path |> File.read! |> process |> IO.puts
end
def process(input) do
input
|> String.split(", ")
|> Enum.reduce(%{x: 0, y: 0, dir: "N"}, &reducer/2)
|> extract_answer
end
defp reducer(<<"R", steps::binary>>, %{x: x, y: y, dir: "N"}), do: %{x: x + (steps |> clean_steps), y: y, dir: "E"}
defp reducer(<<"R", steps::binary>>, %{x: x, y: y, dir: "E"}), do: %{x: x, y: y - (steps |> clean_steps), dir: "S"}
defp reducer(<<"R", steps::binary>>, %{x: x, y: y, dir: "S"}), do: %{x: x - (steps |> clean_steps), y: y, dir: "W"}
defp reducer(<<"R", steps::binary>>, %{x: x, y: y, dir: "W"}), do: %{x: x, y: y + (steps |> clean_steps), dir: "N"}
defp reducer(<<"L", steps::binary>>, %{x: x, y: y, dir: "N"}), do: %{x: x - (steps |> clean_steps), y: y, dir: "W"}
defp reducer(<<"L", steps::binary>>, %{x: x, y: y, dir: "E"}), do: %{x: x, y: y + (steps |> clean_steps), dir: "N"}
defp reducer(<<"L", steps::binary>>, %{x: x, y: y, dir: "S"}), do: %{x: x + (steps |> clean_steps), y: y, dir: "E"}
defp reducer(<<"L", steps::binary>>, %{x: x, y: y, dir: "W"}), do: %{x: x, y: y - (steps |> clean_steps), dir: "S"}
defp clean_steps(steps) do
steps
|> String.trim
|> String.to_integer
end
defp extract_answer(%{x: x, y: y, dir: _}) do
abs(x) + abs(y)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment