Skip to content

Instantly share code, notes, and snippets.

@kohgpat
Created May 21, 2014 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kohgpat/0b79112537a8890de9e6 to your computer and use it in GitHub Desktop.
Save kohgpat/0b79112537a8890de9e6 to your computer and use it in GitHub Desktop.
class Rover
attr_accessor :x, :y
def initialize(x, y, direction)
@x = x
@y = y
@direction = direction
@commands = []
end
def run(commands)
@commands = commands.split('')
@commands.each do |command|
execute_command(command)
end
end
def position
puts "current position: #{@x} #{@y} #{@direction}"
end
private
def execute_command(command)
case command
when 'L'
turn_left
when 'R'
turn_right
when 'M'
move
end
end
def turn_left
case @direction
when 'N'
@direction = 'W'
when 'E'
@direction = 'N'
when 'S'
@direction = 'E'
when 'W'
@direction = 'S'
end
end
def turn_right
case @direction
when 'N'
@direction = 'E'
when 'E'
@direction = 'S'
when 'S'
@direction = 'W'
when 'W'
@direction = 'N'
end
end
def move
case @direction
when 'N'
@y += 1
when 'E'
@x += 1
when 'S'
@y -= 1
when 'W'
@x -= 1
end
end
end
rover = Rover.new(1, 2, 'N')
rover.run('LMLMLMLMM')
rover.position
rover = Rover.new(3, 3, 'E')
rover.run('MMRMMRMRRM')
rover.position
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment