Created
November 26, 2018 02:11
-
-
Save zetashift/e191e069c10c2238bc6a3a53b94f3641 to your computer and use it in GitHub Desktop.
ToyRobot - A snipper
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 ToyRobot do | |
@directions [:north, :east, :south, :west] | |
@directions_to_the_right %{north: :east, east: :south, south: :west, west: :north} | |
@directions_to_the_left Enum.map(@directions_to_the_right, fn {from, to} -> {to, from} end) | |
@table_top_x 4 | |
@table_top_y 4 | |
def place do | |
{:ok, %ToyRobot.Position{}} | |
end | |
# take care of invalid input | |
def place(x, y, _dir) when x < 0 or y < 0 or x > @table_top_x or y > @table_top_y do | |
{:failure, "Invalid position"} | |
end | |
def place(_x, _y, dir) when dir not in @directions do | |
{:failure, "Invalid direction"} | |
end | |
def place(x, y, dir) do | |
%ToyRobot.Position{x: x, y: y, facing: dir} | |
end | |
def report(robot) do | |
%ToyRobot.Position{x: x, y: y, facing: dir} = robot | |
{x, y, dir} | |
end | |
def right(%ToyRobot.Position{facing: facing} = robot) do | |
%ToyRobot.Position{robot | facing: @directions_to_the_right[facing]} | |
end | |
def left(%ToyRobot.Position{facing: facing} = robot) do | |
%ToyRobot.Position{robot | facing: @directions_to_the_left[facing]} | |
end | |
def move(%ToyRobot.Position{x: _, y: y, facing: :north} = robot) when y < @table_top_y do | |
%ToyRobot.Position{robot | y: y + 1} | |
end | |
def move(%ToyRobot.Position{x: x, y: _, facing: :east} = robot) when x < @table_top_x do | |
%ToyRobot.Position{robot | x: x + 1} | |
end | |
def move(%ToyRobot.Position{x: _, y: y, facing: :south} = robot) when y > 0 do | |
%ToyRobot.Position{robot | y: y - 1} | |
end | |
def move(%ToyRobot.Position{x: x, y: _, facing: :west} = robot) when x > 0 do | |
%ToyRobot.Position{robot | x: x - 1} | |
end | |
# fallback function, doesn't change state | |
def move(robot), do: robot | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment