Created
May 21, 2014 07:10
-
-
Save kohgpat/0b79112537a8890de9e6 to your computer and use it in GitHub Desktop.
Revisions
-
kohgpat created this gist
May 21, 2014 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,83 @@ 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