Created
July 8, 2011 13:25
-
-
Save dmitriy-kiriyenko/1071827 to your computer and use it in GitHub Desktop.
Mars rovers from Slava
This file contains 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 characters
class Rover | |
MOVE = { | |
'N' => lambda{ |position| position[:y] += 1 }, | |
'E' => lambda{ |position| position[:x] += 1 }, | |
'S' => lambda{ |position| position[:y] -= 1 }, | |
'W' => lambda{ |position| position[:x] -= 1 } | |
}.freeze | |
ROTATE = { | |
'R' => lambda{ |directions| directions << directions.shift }, | |
'L' => lambda{ |directions| directions.unshift directions.pop } | |
}.freeze | |
def initialize(options = {}) | |
@directions = %w{ N E S W } | |
@plateau, @position, @direction = options[:plateau], options[:position], @directions.index(options[:direction]) | |
end | |
def direction | |
@directions[@direction] | |
end | |
def run(commands) | |
commands.each_char.map do |action| | |
action == 'M' ? MOVE[direction].call(@position) : ROTATE[action].call(@directions) | |
end | |
[@position[:x], @position[:y], direction] | |
end | |
end |
This file contains 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 characters
require 'rover' | |
require 'test/unit' | |
class RoverTest < Test::Unit::TestCase | |
def test_run | |
@rover = Rover.new(:plateau => [5, 5], :position => {:x => 1, :y => 2}, :direction => 'N') | |
assert_equal([1, 3, 'N'], @rover.run('LMLMLMLMM')) | |
end | |
end | |
__END__ | |
INPUT AND OUTPUT | |
Test Input: | |
5 5 | |
1 2 N | |
LMLMLMLMM | |
3 3 E | |
MM R MM RM RR M | |
Expected Output: | |
1 3 N | |
5 1 E | |
========== |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment