Created
December 1, 2016 09:05
-
-
Save EricDykstra/41b46c9a40bf499f97252a81ef32dd8a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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