Skip to content

Instantly share code, notes, and snippets.

@seniorihor
Last active August 9, 2016 01:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seniorihor/07eaf46246f9e887b9bfbe56b542b539 to your computer and use it in GitHub Desktop.
Save seniorihor/07eaf46246f9e887b9bfbe56b542b539 to your computer and use it in GitHub Desktop.
martian_rovers
require_relative "./rover"
input_array = []
file = ARGV[0]
raise "Not specified input file!" if file.to_s.empty?
File.open(file, "r") do |f|
f.each_line { |line| input_array << line }
end
plateau_upper_right = input_array[0].split(" ")
RIGHT_LIMIT = plateau_upper_right[0].to_i
UPPER_LIMIT = plateau_upper_right[1].to_i
def run_rovers(input)
input.delete_at(0)
rovers = []
input.each_index do |index|
if index % 2 == 0
rover_input = input[index].split(" ")
rover_x = rover_input[0].to_i
rover_y = rover_input[1].to_i
rover_face = rover_input[2]
rovers[index] = Rover.new(rover_x, rover_y, rover_face)
else
instructions = input[index].split("")
instructions.each { |instruction| follow_instruction(instruction, rovers[index-1]) }
puts "#{rovers[index-1].x} #{rovers[index-1].y} #{rovers[index-1].facing}"
end
end
end
def follow_instruction(instruction, rover)
case instruction
when "L" then rover.turn_left
when "R" then rover.turn_right
when "M" then rover.move_forward
end
end
run_rovers(input_array)
5 5
1 2 N
LMLMLMLMM
3 3 E
MMRMMRMRRM
class Rover
attr_accessor :x, :y, :facing
def initialize(x, y, facing)
@x = x
@y = y
@facing = facing
end
def turn_left
case @facing
when "N" then @facing = "W"
when "S" then @facing = "E"
when "E" then @facing = "N"
when "W" then @facing = "S"
end
end
def turn_right
case @facing
when "N" then @facing = "E"
when "S" then @facing = "W"
when "E" then @facing = "S"
when "W" then @facing = "N"
end
end
def move_forward
case @facing
when "N"
@y += 1 if @y < UPPER_LIMIT
when "S"
@y -=1 if @y > 0
when "E"
@x += 1 if @x < RIGHT_LIMIT
when "W"
@x -= 1 if @x > 0
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment