Skip to content

Instantly share code, notes, and snippets.

@nerboda
Last active September 26, 2016 23:39
Show Gist options
  • Save nerboda/8cbd94d043c0fe0b25fa7426e5d2037a to your computer and use it in GitHub Desktop.
Save nerboda/8cbd94d043c0fe0b25fa7426e5d2037a to your computer and use it in GitHub Desktop.
Weekly Challenges - Robot Simulator
# Robots can: turn left, turn right, or advance
class Robot
attr_reader :bearing
def initialize
@bearing = :north
@x = 0
@y = 0
end
def orient(direction)
raise ArgumentError unless [:north, :south, :east, :west].include? direction
@bearing = direction
end
def coordinates
[@x, @y]
end
def turn_right
directions = { north: :east, east: :south, south: :west, west: :north }
@bearing = directions[bearing]
end
def turn_left
directions = { north: :west, west: :south, south: :east, east: :north }
@bearing = directions[bearing]
end
def at(x, y)
@x = x
@y = y
end
def advance
value = { north: 1, east: 1, south: -1, west: -1 }[bearing]
[:east, :west].include?(bearing) ? @x += value : @y += value
end
end
# Place Robots on a grid and simulate their movements
# based on a string of commands.
class Simulator
def instructions(command)
commands = { 'L' => :turn_left, 'R' => :turn_right, 'A' => :advance }
command.chars.map { |letter| commands[letter] }
end
def place(robot, options = {})
robot.orient(options[:direction])
robot.at(options[:x], options[:y])
end
def evaluate(robot, command)
instructions(command).each do |method|
robot.send(method)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment