Last active
December 30, 2015 13:09
-
-
Save JFickel/7833928 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 RoversController | |
attr_accessor :grid, :rovers | |
def initialize(x, y) | |
@rovers = [] | |
end | |
def add_rover(x, y, direction) | |
@rovers << Rover.new({x: x.to_i, y: y.to_i}, direction) | |
end | |
def execute_instructions(instructions) | |
rover = @rovers.last | |
instructions.each do |action| | |
case action | |
when 'L' | |
rover.rotate_left | |
when 'R' | |
rover.rotate_right | |
when 'M' | |
rover.move | |
end | |
end | |
end | |
end | |
class Rover | |
attr_accessor :direction, :position | |
def initialize(position, direction) | |
@direction = direction | |
@position = position | |
end | |
def rotate_left | |
case @direction | |
when 'N' | |
@direction = 'W' | |
when 'E' | |
@direction = 'N' | |
when 'S' | |
@direction = 'E' | |
when 'W' | |
@direction = 'S' | |
end | |
end | |
def rotate_right | |
case @direction | |
when 'N' | |
@direction = 'E' | |
when 'E' | |
@direction = 'S' | |
when 'S' | |
@direction = 'W' | |
when 'W' | |
@direction = 'N' | |
end | |
end | |
def move | |
case direction | |
when 'N' | |
@position[:y] += 1 | |
when 'E' | |
@position[:x] += 1 | |
when 'S' | |
@position[:y] -= 1 | |
when 'W' | |
@position[:x] -= 1 | |
end | |
end | |
end | |
file = File.new(ARGV.first) | |
input = file.map(&:chomp) | |
plateau_size = input.shift.split | |
rc = RoversController.new(plateau_size.first, plateau_size.last) | |
input.each_slice(2) do |rl, ri| | |
location = rl.split | |
instructions = ri.split('') | |
rc.add_rover(location[0], location[1], location[2]) | |
rc.execute_instructions(instructions) | |
end | |
rc.rovers.each do |rover| | |
puts "#{rover.position[:x]} #{rover.position[:y]} #{rover.direction}" | |
end |
This file contains hidden or 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
5 5 | |
1 2 N | |
LMLMLMLMM | |
3 3 E | |
MMRMMRMRRM |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment