In this post, we will be taking onthe Mars Rover Kata. This challenge entails implementing aRover
which can drive from grid cell to grid cell on a grid based on commands. Commands are passed as a string of individual instructions, these instructions can be to move (M), turn left (L) or turn right (R).
Task solution
Tests
const{Rover}=require("./rover");letrover;beforeEach(()=>{rover=newRover();});describe("rover",()=>{it("Has an initial position of 0",()=>{expect(rover.direction).toEqual(0);});it("Can move given instructions",()=>{expect(rover.currentPosition).toEqual([0,0]);rover.move("LMRMM");expect(rover.currentPosition).toEqual([0,2]);});it("Translates direction correctly",()=>{rover.translateInstructions(["L","L","R"]);expect(rover.direction).toEqual(-1);});it("Can move postion correctly",()=>{rover.move("M");expect(rover.currentPosition).toEqual([0,1]);rover.move("RM");expect(rover.currentPosition).toEqual([1,1]);rover.move("RM");expect(rover.currentPosition).toEqual([1,0]);rover.move("RM");expect(rover.currentPosition).toEqual([0,0]);rover.move("M");expect(rover.currentPosition).toEqual([9,0]);rover.move("LM");expect(rover.currentPosition).toEqual([9,9]);rover.move("RRM");expect(rover.currentPosition).toEqual([9,0]);rover.move("RM");expect(rover.currentPosition).toEqual([0,0]);});it("throws when an invalid move is provided",()=>{expect(()=>rover.move("X")).toThrowErrorMatchingSnapshot();});});
Each test uses a newRover
instance and cover the following cases:
- Initial state
- Instruction execution
- Movement of the rover
- Error handling
We can also see that we are working with anx
andy
coordinate system for the rovers current position. You may also have noticed the integer based direction of the rover. It will make more sense as to why I chose to do directionality in this way once the implementation is seen but in short, we will have an array of potential directions, each of these will represent the points of a compass (North, South, East, West).
When we wish to see which direction we should move, we can usethe%
(modulo) operator which I explained in an earlier article to access the relevant direction. Since we are using 4 compass points we can only ever receive values between -4 and 4 when using any number modulo the count of compass points. I chose to only allow moves on positive values but we could useMath.abs
to convert the negatives to positives and use them but the programme behaviour would change from how it is currently setup in the tests. Just as a side note, here are some examples of potential actions based on a direction modulod by the 4 compass points:
Direction | Compass point | Action |
---|---|---|
-1 | -1 % 4 = -1 = None | Don't move |
2 | 2 % 4 = 2 = South | Move down |
5 | 5 % 4 = 1 = East | Move right |
Implementation
classRover{constructor(gridDimension=10){this.currentPosition=[0,0];this.direction=0;this.compassPoints=["N","E","S","W"];this.gridDimension=gridDimension;}move(instructions){constindividualInstructions=instructions.split("");this.translateInstructions(individualInstructions);}shiftUp(){let[x,y]=this.currentPosition;if(y===this.gridDimension-1)y=0;elsey=++y;this.currentPosition=[x,y];}shiftDown(){let[x,y]=this.currentPosition;if(y===0)y=this.gridDimension-1;elsey=--y;this.currentPosition=[x,y];}shiftLeft(){let[x,y]=this.currentPosition;if(x===0)x=this.gridDimension-1;elsex=--x;this.currentPosition=[x,y];}shiftRight(){let[x,y]=this.currentPosition;if(x===this.gridDimension-1)x=0;elsex=++x;this.currentPosition=[x,y];}getCompassHeading(){returnthis.compassPoints[this.direction%this.compassPoints.length];}shiftRoverPosition(){constmoveDirection=this.getCompassHeading();if(moveDirection==="N")this.shiftUp();elseif(moveDirection==="S")this.shiftDown();elseif(moveDirection==="E")this.shiftRight();elseif(moveDirection==="W")this.shiftLeft();}translateInstructions(instructions){instructions.forEach(instruction=>{if(instruction==="L")this.direction--;elseif(instruction==="R")this.direction++;elseif(instruction==="M")this.shiftRoverPosition();elsethrownewError("Invalid instruction provided");});}}module.exports={Rover};
We interact with theRover
instance by calling themove
method, this method takes 1 parameter, a string of instructions. This string is split into the individual characters and passed as an array into thetranslateInstructions
function. Each instruction is checked and if the command is to move left (L), we add 1 from the currentdirection
. If the command is to move right (R), we add one to the currentdirection
. If the command is to move, we call theshiftRoverPosition
method and finally, if the instruction is not recognised, we throw and error. TheshiftRoverPosition
method calls thegetCompassHeading
method which is where we try to get our value from the compass headings:
getCompassHeading(){returnthis.compassPoints[this.direction%this.compassPoints.length];}
If we get back aN
,E
,S
orW
, we move up, right, down or left respectively, in practice this merely means altering thex
andy
coordinates of the rover.
Conclusions
I actually did this Kata as part of an interview a while back and this was my solution. I will say though that this isn't the whole Kata, it is a stripped down version that the company I interviewed at used for their tech interview pair-programming session. I recommend trying it out yourself to see what you can come up with or extending the functionality for your rover to make it do even more than just move around a grid, why not give it a try and see what you come up with?
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse