Position of robot after given movements in C++


In this problem, we are given a robot that moves in all four directions but only one move. The directions are up(‘U’), down(‘D’), left(‘L’), right(‘R’). And we are given a string that contains initials of directions of the number. Our task is to print the final position of the robot, given the initial position of the robot is (0,0).

Let’s take an example to understand the problem

Input − input: ‘LDRRUL’

Output − (0, 0)

Explanation

L (left) : (0,0) -> (-1,0)
D (down) : (-1,0) -> (-1, -1)
R (right) : (-1, -1) -> (0, -1)
R (right) : (0, -1) -> (1, -1)
U(up) : (1, -1) -> (1, 0)
L(left) : (1, 0) -> (0, 0)

To solve this problem, we will count the total moves in the x-axis and the y-axis direction. For x-coordinate, increase the count for Right move and decrease count for a left move. For y-coordinate, increase the count for the up move and down count for a left move.

Example

Program to show the implementation of our solution

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
void robotMoved(string move) {
   int xAxis, yAxis;
   int l=move.size();
   for (int i = 0; i < l; i++) {
      if (move[i]=='U')
         yAxis++;
      else if (move[i]=='D')
         yAxis--;
      else if (move[i]=='L')
         xAxis--;
      else if (move[i]=='R')
         xAxis++;
   }
   cout<<"Final Position of the robot is : ("<<xAxis<<", "<<yAxis<<")"<<endl;
}
int main() {
   string move="URLLDDRRUDUDDRU";
   robotMoved(move);
   return 0;
}

Output

Final Position of the robot is : (32744, -274873553)

Updated on: 17-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements