Sha256: 13561e25b663129c7870ce0729ee257c5b633b1ef78b50a216ea4ab38c3cb269

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

require "forwardable"
require "nasa_rovers/plateau"
require "nasa_rovers/position"

module NasaRovers
  class Rover
    extend Forwardable

    MAPPING = {
      M: :move,
      L: :left,
      R: :right
    }

    INST_ROWS = 2

    def self.factory(data, plateau, position_class=Position)
      position = position_class.factory(data)
      new(position, plateau)
    end

    def self.instruct(data, plateau_class=Plateau)
      plateau = plateau_class.factory(data.shift)
      data.each_slice(INST_ROWS).reduce([]) do |rovers, rows|
        position, instructions = rows
        rover = factory(position, plateau)
        rover.call(instructions)
        rovers << rover
      end
    end

    def_delegators :@position, :cardinal, :coord, :to_s

    attr_reader :plateau, :position

    def initialize(position, plateau)
      @position = position
      @plateau = plateau
    end

    def call(data)
      instructions(data).each do |inst|
        action = MAPPING.fetch(inst) { :stay }
        send(action)
      end
    end

    private def instructions(data)
      data.split("").map(&:strip).map(&:to_sym)
    end

    private def left
      position.cardinal = CARDINALS[cardinal_idx-1]
    end

    private def right
      idx = CARDINALS[cardinal_idx+1] ? cardinal_idx+1 : 0
      position.cardinal = CARDINALS[idx]
    end

    private def cardinal_idx
      CARDINALS.index(cardinal)
    end

    private def move
      case cardinal
      when "N"
        coord.y += 1
        coord.y = plateau.top_rt.y unless plateau.include?(coord)
      when "E"
        coord.x += 1
        coord.x = plateau.top_rt.x unless plateau.include?(coord)
      when "S"
        coord.y -= 1
        coord.y = plateau.bot_lt.y unless plateau.include?(coord)
      when "W"
        coord.x -= 1
        coord.x = plateau.bot_lt.x unless plateau.include?(coord)
      end
    end

    private def stay; end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nasa_rovers-1.0.1 lib/nasa_rovers/rover.rb