Skip to content

Instantly share code, notes, and snippets.

@krishicks
Created March 7, 2011 03:19
Show Gist options
  • Save krishicks/858009 to your computer and use it in GitHub Desktop.
Save krishicks/858009 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
class RoverRemote
def initialize(cmds)
parse(cmds)
end
def parse(cmds)
cmds.split("\n").each do |cmd|
case cmd
when /(\d\s)+[NSEW]/
@rover = WallE.new(cmd)
when /[LRM]/
@rover.do(cmd)
end
end
end
end
class WallE
def initialize(cmd)
x, y, @facing = cmd.split(" ")
@x, @y = x.to_i, y.to_i
end
def do(cmd)
cmd.split('').each { |cmd| cmd =~ /M/ ? move : turn(cmd) }
report
end
def turn(dir)
c = %w{ N E S W }
p = c.index(@facing)
@facing = case dir
when "L" then c[p-1]
when "R" then c[p+1] || c[0]
end
end
def move
case @facing
when "N" then @y+=1
when "S" then @y-=1
when "E" then @x+=1
when "W" then @x-=1
end
end
def report
puts "#{@x} #{@y} #{@facing}"
end
end
RoverRemote.new("5 5\n1 2 N\nLMLMLMLMM\n3 3 E\nMMRMMRMRRM")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment