Created
October 5, 2018 23:28
-
-
Save ddresselhaus/441c4120d0c4f84bb4510c5a34bc5865 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 Rover do | |
@directions ["N", "E", "S", "W"] | |
def execute(location_string, moves_string) do | |
location = parse_location(location_string) | |
moves = parse_moves(moves_string) | |
process_move(location, moves) | |
end | |
def process_move(location, []), do: location | |
def process_move({x, y, direction}, [move | remaining_moves]) do | |
new_direction = process_direction(direction, move) | |
{new_x, new_y} = process_placement({x, y}, direction, move) | |
process_move({new_x, new_y, new_direction}, remaining_moves) | |
end | |
def parse_location(location) do | |
split = String.split(location, " ") | |
{x, _} = Enum.at(split, 0) |> Integer.parse() | |
{y, _} = Enum.at(split, 1) |> Integer.parse() | |
direction = Enum.at(split, 2) | |
{x, y, direction} | |
end | |
def parse_moves(moves_string) do | |
String.split(moves_string, "") |> Enum.filter(fn x -> String.length(x) > 0 end) | |
end | |
def process_placement({x, y}, direction, move) when move == "M" do | |
case direction do | |
"N" -> {x, y + 1} | |
"E" -> {x + 1, y} | |
"S" -> {x, y - 1} | |
"W" -> {x - 1, y} | |
end | |
end | |
def process_placement(coordinates, direction, move), do: coordinates | |
def process_direction(direction, move) when move in ["L", "R"] do | |
index = @directions |> Enum.find_index(fn x -> x == direction end) | |
new_index = | |
case move do | |
"L" -> | |
adjust_index(index - 1) | |
"R" -> | |
adjust_index(index + 1) | |
_ -> | |
index | |
end | |
Enum.at(@directions, new_index) | |
end | |
def process_direction(direction, move), do: direction | |
def adjust_index(index) do | |
index |> rem(Enum.count(@directions)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment