10
\$\begingroup\$

Please look at a small piece of code I wrote and provide some thoughts, critiques and any feedback you think is needed.

The code is here along with the problem I have attempted to solve and I look forward to hearing all your thoughts on it.

The Problem

The surface of Mars can be modelled by a rectangular grid around which robots are able to move according to instructions provided from Earth. You are to write a program that determines each sequence of robot positions and reports the final position of the robot.

A robot position consists of a grid coordinate (a pair of integers: x-coordinate followed by y-coordinate) and an orientation (N, S, E, W for north, south, east, and west).

A robot instruction is a string of the letters "L", "R", and "F" which represent, respectively, the instructions:

  • Left: the robot turns left 90 degrees and remains on the current grid point.
  • Right: the robot turns right 90 degrees and remains on the current grid point.
  • Forward: the robot moves forward one grid point in the direction of the current orientation and maintains the same orientation.

The direction North corresponds to the direction from grid point (x, y) to grid point (x, y+1). There is also a possibility that additional command types maybe required in the future and provision should be made for this. Since the grid is rectangular and bounded (...yes Mars is a strange planet), a robot that moves "off" an edge of the grid is lost forever. However, lost robots leave a robot "scent" that prohibits future robots from dropping off the world at the same grid point. The scent is left at the last grid position the robot occupied before disappearing over the edge. An instruction to move "off" the world from a grid point from which a robot has been previously lost is simply ignored by the current robot.

The Input

The first line of input is the upper-right coordinates of the rectangular world, the lower-left coordinates are assumed to be 0, 0.

The remaining input consists of a sequence of robot positions and instructions (two lines per robot). A position consists of two integers specifying the initial coordinates of the robot and an orientation (N, S, E, W), all separated by whitespace on one line. A robot instruction is a string of the letters "L", "R", and "F" on one line.

Each robot is processed sequentially, i.e., finishes executing the robot instructions before the next robot begins execution.

The maximum value for any coordinate is 50.

All instruction strings will be less than 100 characters in length.

The Output

For each robot position/instruction in the input, the output should indicate the final grid position and orientation of the robot. If a robot falls off the edge of the grid the word "LOST" should be printed after the position and orientation.

Sample Input

  • 1 1 E RFRFRFRF
  • 3 2 N FRRFLLFFRRFLL
  • 0 3 W LLFFFLFLFL

Sample Output

  • 1 1 E
  • 33 N LOST
  • 2 3 S

My Solution

//  robot factory
//  -------------------------------------------------------------------------------------
//  the robotFactory is a factory method used for creating new robots to explore Mars.
//  there is a dependency on Underscore for some object extension although this could
//  have been written as a constructor or in the future using the native Object.assign().
//
//  ==  EXAMPLE   =======================================================================
//
//  var robotFactory = require('./src/robot'),
//      dave = robotFacotry({x: 27, y: 12, heading: 'E'});
//
//  dave.instruct('lrlflfrlflrfffrlfl');
//  -------------------------------------------------------------------------------------

;(function (_, undefined) {

  'use strict';

  module.exports = (function () {
    var losses  = [],
        compass = ['N', 'E', 'S', 'W'],
        bounds  = {
          min: { x: 0,  y: 0  },
          max: { x: 50, y: 25 }
        };

    return function (options) {
      var defaults = _.extendOwn({
            x: 0,
            y: 0,
            heading: 'N'
          }, options),

          //  moves
          //  -------------------------------------
          //  a collection of the robot's movements
          //  which could be useful.
          //  -------------------------------------
          moves = [],

          //  is within bounds?
          //  --------------------------------------
          //  check whether a set of coordinates are
          //  within a set boundary.
          //  ======================================
          //  @arg      {object}  coords
          //  @returns  {boolean}
          //  --------------------------------------
          isWithinBounds = function (coords) {
            if (!coords instanceof Object)
              throw new TypeError();

            var lastMove = moves[moves.length - 1],
                move     = _.extend({}, lastMove, coords);

            return ((move.x >= bounds.min.x && move.x <= bounds.max.x) &&
                    (move.y >= bounds.min.y && move.y <= bounds.max.y));
          },

          //  add move
          //  ----------------------------------------------------------------
          //  checks whether the latest coordinates are within the boundaries
          //  or if it the robot has been lost, if it is it'll add a new entry
          //  to the moves collection else it will also add the coordinates to
          //  the losses collection.
          //  ================================================================
          //  @arg      {object}  coords
          //  ----------------------------------------------------------------
          addMove = function (coords) {
            if (!coords instanceof Object)
              throw new TypeError();

            var lastMove = moves[moves.length - 1],
                move     = _.extend({}, lastMove, coords);

            if (lastMove.lost)
              return;

            if (isWithinBounds(move)) {
              moves.push(move);
            } else {
              if (!(_.filter(losses, function (loss) {
                return [loss.x, loss.y].toString() === [move.x, move.y].toString();
              }).length)) {
                moves.push(_.extend({lost: true}, move));
                losses.push(move);
              }
            }
          },

          //  turn
          //  -------------------------------------------
          //  gets the current heading of the robot,
          //  updates the heading and calls addMove to
          //  add a new movement to the moves collection.
          //  ===========================================
          //  @arg      {number}  dir
          //  -------------------------------------------
          turn = function (dir) {
            if (typeof dir !== 'number')
              throw new TypeError();

            var lastMove = moves[moves.length - 1],
                currentHeading = compass.indexOf(lastMove.heading);

            currentHeading = currentHeading + dir;

            if (currentHeading < 0)
              currentHeading = 3;

            else if (currentHeading > 3)
              currentHeading = 0;

            addMove({
              heading: compass[currentHeading]
            });
          },

          //  move
          //  -------------------------------------------------
          //  checks which way to move the robot and then calls
          //  the addMove method to perform the checks and add
          //  to the collection.
          //  -------------------------------------------------
          move = function () {
            var move = {},
                lastMove = moves[moves.length - 1];

            if (lastMove.heading.match(/n/i))
              move.y = lastMove.y + 1;

            else if (lastMove.heading.match(/e/i))
              move.x = lastMove.x + 1;

            else if (lastMove.heading.match(/s/i))
              move.y = lastMove.y - 1;

            else if (lastMove.heading.match(/w/i))
              move.x = lastMove.x - 1;

            addMove(move);
          };

      //  add an initial position when the robot created.
      moves.push({
        x: defaults.x,
        y: defaults.y,
        heading: defaults.heading
      });

      return {
        //  instruct
        //  ------------------------------------------------------
        //  this method allows you to give your robot instructions
        //  on how to move over the surface of Mars.
        //  ======================================================
        //  @arg      {string}  instructions
        //  @returns  {string}  last position
        //  ------------------------------------------------------
        instruct: function (instructions) {
          if (typeof instructions !== 'string')
            throw new TypeError();

          if (instructions.length >= 100)
            throw new Error('Instruction string must be less than 100 characters');

          if (instructions.match(/^[l|r|f]*$/i)) {
            instructions.split('').forEach(function (instruction) {
              if (instruction.match(/l/i))
                turn(-1);

              else if (instruction.match(/r/i))
                turn(1);

              else if (instruction.match(/f/i))
                move();
            });

            var lastMove = moves[moves.length - 1];

            return lastMove.x + ' ' + lastMove.y + ' ' + lastMove.heading +
              ((lastMove.lost) ? ' LOST' : '');
          } else
            throw new Error('Instructions can only include a combination of L, R and F');
        }
      };
    };
  } ());

} (require('underscore')));

Full solution with Jasmine tests

Working example

\$\endgroup\$
1
\$\begingroup\$

Just a quick thing on the regular expression of your instruct function.

If you pass an empty string, /^[l|r|f]*$/i will find a match, but the robot won't do any moves, so it won't return any value, failing the purpose of the robot.

Maybe force instructions with at least one command /^[l|r|f]+$/i

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.