Position of a robot after given movements in C++

In this tutorial, we will write a C++ program to find the final position of a robot from the given movements.
Let us consider a robot that can move in a 2-Dimensional space, we need to find the final position of the robot in the x-y plane. The robot can move in the following directions,

  1. Up (U or u)
  2. Down (D or d)
  3. Left (L or l)
  4. Right (R or r)

The input string will contain the initial letter of the direction from which we will calculate the final position. Let us consider the basic steps required to calculate the position of the robot.

  1. Input the string that contains the direction.
  2. Traverse the string and count the movement in each direction.
  3. Calculate and print the position in the x-y plane.
    Exit the program in case of an invalid character in the input string.

C++ Program to Find the Position of Robot

#include <bits/stdc++.h> 
using namespace std; 

//Funcion to find final position  
void findPos(string dir) 
{ 
    int up = 0, down = 0; 
    int left = 0, right = 0; 
  
    for (int i = 0; dir[i] != '\0' ; i++) { 
  
        //Counts each direction
        if (dir[i] == 'U' || dir[i] == 'u') 
            up++; 
        else if (dir[i] == 'D' || dir[i] == 'd') 
            down++; 
        else if (dir[i] == 'L' || dir[i] == 'l') 
            left++; 
        else if (dir[i] == 'R' || dir[i] == 'r') 
            right++; 
        
        //In case of illegal character in the string 
        else
        {
            cout<<"Position Unable to Find, Enter Correct Direction.";
            exit(0);
        }
    } 
  
    //Final position of robot 
    cout << "Final Position of the Robot: ("
         << (right - left)<< ", " << (up - down)<< ")"; 
} 
  
int main() 
{ 
    string dir;
    
    //Input the direction string
    cout<<"Enter the Direction String:  ";
    cin>>dir;
    
    //Function call to calculate position 
    findPos(dir); 
    
    return 0; 
}

Output

In case of entering proper characters in the string,

Enter the Direction String: UUURLLDDLRRRLRDUURDLR
Final Position of the Robot: (2,1)

In case of entering invalid characters in the string,

Enter the Direction String: LLRDRLUDRSURLLD
Position Unable to Find, Enter Correct Direction.

 

Leave a Reply