Skip to content

Instantly share code, notes, and snippets.

@mkweick
Last active November 26, 2015 17:18
Show Gist options
  • Save mkweick/7bb948f97376d03ea1ab to your computer and use it in GitHub Desktop.
Save mkweick/7bb948f97376d03ea1ab to your computer and use it in GitHub Desktop.
Robot Simulator
class Robot
attr_accessor :bearing, :coordinates
def orient(direction)
if [:north, :east, :south, :west].include? direction
self.bearing = direction
else
raise ArgumentError, "Invalid direction"
end
end
def turn_right
turn('r')
end
def turn_left
turn('l')
end
def advance
case bearing
when :north then self.coordinates[1] += 1
when :east then self.coordinates[0] += 1
when :south then self.coordinates[1] -= 1
when :west then self.coordinates[0] -= 1
end
end
def at(x, y)
self.coordinates = [x, y]
end
private
def turn(direction)
if direction == 'r'
case bearing
when :north then self.bearing = :east
when :east then self.bearing = :south
when :south then self.bearing = :west
when :west then self.bearing = :north
end
else
case bearing
when :north then self.bearing = :west
when :east then self.bearing = :north
when :south then self.bearing = :east
when :west then self.bearing = :south
end
end
end
end
class Simulator
def place(robot, args)
robot.at(args[:x], args[:y])
robot.orient(args[:direction])
end
def evaluate(robot, input_commands)
instructions(input_commands).each do |action|
case action
when :turn_right then robot.turn_right
when :turn_left then robot.turn_left
when :advance then robot.advance
end
end
end
def instructions(input_commands)
input_commands.split('').map do |command|
case command
when 'R' then :turn_right
when 'L' then :turn_left
when 'A' then :advance
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment