Skip to content

Instantly share code, notes, and snippets.

@epitron
Created June 11, 2015 20:18
Show Gist options
  • Save epitron/68c277e92384c12ce419 to your computer and use it in GitHub Desktop.
Save epitron/68c277e92384c12ce419 to your computer and use it in GitHub Desktop.
# Rover
# - move
# - turn_left
# - turn_right
class Rover
attr_reader :x, :y, :direction
COMPASS = %w[N E S W]
DIRECTION_VECTORS = {
"N" => [0,1],
"S" => [0,-1],
"E" => [1,0],
"W" => [-1,0],
}
def initialize(x,y,direction,width=10,height=10)
@x, @y, @direction = x, y, direction
@width, @height = width, height
end
def move
dx, dy = DIRECTION_VECTORS[@direction]
@x += dx
@y += dy
@x = 0 if @x < 0
@x = @width if @x > @width
@y = 0 if @y < 0
@y = @height if @y > @height
end
def turn(n=1)
pos = COMPASS.index(@direction)
@direction = COMPASS.rotate(n)[pos]
end
def turn_left
turn(-1)
end
def turn_right
turn(1)
end
def read_instruction(i)
case i
when "M"
move
when "L"
turn_left
when "R"
turn_right
end
puts self
end
def to_s
"<Rover: #{x},#{y} facing #{direction}>"
end
end
r = Rover.new(1,1,"N",5,5)
# r.move
# r.turn_left
# r.turn_right
# r.read_instruction("M")
# r.read_instruction("L")
# r.read_instruction("R")
input = "RMMMMLMMMLRLLLRRRMMM"
input.each_char do |c|
r.read_instruction(c)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment