Skip to content

Instantly share code, notes, and snippets.

@korakotlee
Created July 18, 2019 17:48
Show Gist options
  • Save korakotlee/8f1a992eca15d2d16e999364d578343b to your computer and use it in GitHub Desktop.
Save korakotlee/8f1a992eca15d2d16e999364d578343b to your computer and use it in GitHub Desktop.
Ruby Mars Rover
class Rover
# attr_reader :x, :y, :direction
def initialize(x, y, dir)
@x = x
@y = y
@dir = dir
end
def to_s
puts "#{@x} #{@y} #{@dir}"
end
def command(s)
s.split('').each do |cmd|
if cmd == 'M' # move
case @dir
when 'N'
@y += 1
when 'S'
@y -= 1
when 'W'
@x -= 1
when 'E'
@x += 1
end
else # turn
dir = Direction.new(@dir)
case cmd
when 'L'
@dir = dir.turn_left
when 'R'
@dir = dir.turn_right
end
end
end
puts self
end
end
class Direction
DIRECTION = ['N','E','S','W']
def initialize(dir)
@i = DIRECTION.find_index {|d| d == dir}
end
def turn_left
@i -= 1
@i = 3 if @i < 0
return DIRECTION[@i]
end
def turn_right
@i += 1
@i = 0 if @i > 3
return DIRECTION[@i]
end
end
# Test Input:
rover = Rover.new(1, 2, 'N')
rover.command('M')
# Expected Output:
# 1 3 N
# Test Input:
rover = Rover.new(1, 2, 'N')
rover.command('LMLMLMLMM')
# Expected Output:
# 1 3 N
# Test Input:
rover = Rover.new(3, 3, 'E')
rover.command('MMRMMRMRRM')
# Expected Output:
# 5 1 E
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment