Skip to content

Instantly share code, notes, and snippets.

@kohgpat
Created May 21, 2014 07:10
Show Gist options
  • Save kohgpat/0b79112537a8890de9e6 to your computer and use it in GitHub Desktop.
Save kohgpat/0b79112537a8890de9e6 to your computer and use it in GitHub Desktop.

Revisions

  1. kohgpat created this gist May 21, 2014.
    83 changes: 83 additions & 0 deletions rover.rb
    Original 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