Robot Simulator in JavaScript

  for-loop, javascript

All,

I am trying to work on a simple solution in JS.

enter image description here

I have a program that currently prints out a direction of a simple simulation. But what am seeking to do is to currently embed the x and y coordinates as it loops through.

For example:

  1. If for example, I have a string code like "LLRAA". This is what it means, Start your index facing "North" with {x,y} = {0,0}. So during the loop, when I see L: Move Left=West and the second character, L is Left: move to South and sees R= Move Right = West. Now at West, if it sees A, it means decrement x coordinate by 1, so the coordinates will be {-1,0} and still stand at West. For the next iteration, A decrease x by -1 so it will be {-2,0}.

So final output is {"x: " + x + " y:" + " bearing:" + d} = {x:-2, y:0, bearing:West}

My code is below for testing:

function robotSimulator(param){

    let counter = 0;
    let d = "";
    let x = 0;
    let y = 0;

    //Using this too see if the direction for the bearing is a clockwise movement or anticlockwise one
    for(let i=0; i < param.length; i++){
        if(param[0] == "n"){
            return null;
        }

        else if(param[i] == 'L'){
            counter--;
        }
        else if(param[i] == 'R'){
            counter++;
        }
        // console.log(counter);

     //If count is positive, then it means it is moving clockwise direction
    if(counter > 0){
        if(counter % 4 == 0){
            d = "North";
        }
        else if(counter % 4 == 1){
            d = "East";
        }
        else if(counter % 4 == 2){
            d = "South";
        }
        else if(counter % 4 == 3){
            d = "West";
       }      
    }
    
    //If count is negative that means the direction is anticlockwise
    if(counter < 0){
        if (counter % 4 == 0)
                d = "North";
            else if (counter % 4 == -1)
                d = "West";
            else if (counter % 4 == -2)
                d = "South";
            else if (counter % 4 == -3)
                d = "East";
    }
    }
    
    
    return d;
    return ("x:  "+ x + "  y:" + y);
}

console.log(robotSimulator("RRLLL"));

Source: Ask Javascript Questions

LEAVE A COMMENT