How to Create C++ Program to Robot Return to Origin ?

  C & C ++ Interview Q&A

Dear readers, this article read today how to make C ++ program to robot return to origin?

If there is a robot and its starting position is (0, 0). If we have a sequence of its moves, then we need to check whether this robot ends (0, 0) after completing its moves.

The gait sequence is given as a string, and the character moves [i] representing its ith gait. The symbols are right for R, left for L, U for up, and D for down. If the robot returns to the original after completing all its moves, return true. Otherwise the liar returns.

So, if the input is like “RRULLD”, the output will be right, right to two-unit, then go up, then two units left then down, so this is the starting position.

Example for Robot Return to Origin in C++

#include <bits/stdc++.h>
using namespace std;
class returntoOriginProg{
public:
   bool judgeCircle(string moves) {
      int l = moves.length();
      if (l == 0) {
         return true;
      }
      int lft = 0, up = 0;
      for (int i = 0; i < l; i++) {
         if (moves[i] == 'L') {
            lft++;
         }
         if (moves[i] == 'R') {
            lft--;
         }
         if (moves[i] == 'U') {
            up++;
         }
         if (moves[i] == 'D') {
            up--;
         }
      }
      if (lft == 0 && up == 0) {
         return true;
      }
      return false;
   }
};
main(){
   returntoOriginProg ob;
   cout << (ob.judgeCircle("RRULLD"));
}

Output

1

LEAVE A COMMENT