Created
October 24, 2015 06:16
-
-
Save falonofthetower/d955ff6397d47aaf9e34 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
class Robot | |
attr_reader :directions | |
def initialize | |
@directions = [:north, :east, :south, :west] | |
end | |
def orient(direction) | |
if invalid_direction? direction | |
raise ArgumentError | |
else | |
orient_to direction | |
end | |
end | |
def invalid_direction?(direction) | |
!directions.include?(direction) | |
end | |
def orient_to(direction) | |
until self.bearing == direction | |
self.turn_right | |
end | |
end | |
def bearing | |
directions[0] | |
end | |
def turn_right | |
directions.push directions.shift | |
end | |
def turn_left | |
directions.unshift directions.pop | |
end | |
def at(x,y) | |
@x = x | |
@y = y | |
end | |
def coordinates | |
[@x, @y] | |
end | |
def advance | |
case self.bearing | |
when :north | |
@y += 1 | |
when :south | |
@y -= 1 | |
when :east | |
@x += 1 | |
when :west | |
@x -= 1 | |
end | |
end | |
end | |
class Simulator | |
INSTRUCTIONS = { turn_left: 'L', turn_right: 'R', advance: 'A' } | |
def instructions(commands) | |
command_list(commands).map { |command| INSTRUCTIONS.key(command) } | |
end | |
def command_list(commands) | |
commands.split('') | |
end | |
def place(robot, options ={}) | |
robot.at(options[:x], options[:y]) | |
robot.orient(options[:direction]) | |
end | |
def evaluate(robot, commands) | |
self.instructions(commands).map { |command| robot.send(command) } | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment