Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

James Robb
James Robb

Posted on

     

Mars Rover

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();});});
Enter fullscreen modeExit fullscreen mode

Each test uses a newRover instance and cover the following cases:

  1. Initial state
  2. Instruction execution
  3. Movement of the rover
  4. 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:

DirectionCompass pointAction
-1-1 % 4 = -1 = NoneDon't move
22 % 4 = 2 = SouthMove down
55 % 4 = 1 = EastMove 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};
Enter fullscreen modeExit fullscreen mode

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];}
Enter fullscreen modeExit fullscreen mode

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I like to build cool things, work with nice people and help others where I can. Currently I'm an engineering manager for a fintech startup and historically a serial founder & freelancer software dev.
  • Location
    München, Deutschland 🇩🇪
  • Education
    The Open University
  • Work
    Engineering Manager @ Deutsche Fintech Solutions GmbH
  • Joined

More fromJames Robb

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp