Find the direction from given string in C++


Suppose we have a string which contains only L and R, this denotes left rotation and right rotation respectively, we have to find the final direction of pivot. Here directions are north(N), east(E), south(S) and west(W). We are assuming that the pivot is pointed towards north(N) in a compass.

So, if the input is like "RRLRLLR", then the output will be E, as initial direction is N, RR will point to S, then LR will point to the same N again, then LL will point to previous position N, then R will point to E. So E is the final.

To solve this, we will follow these steps −

  • count := 0

  • direction := a blank string

  • for initialize i := 0, when i − length of s, update (increase i by 1), do −

    • if s[i] is same as 'L', then −

      • (decrease count by 1)

    • Otherwise

      • (increase count by 1)

  • if count > 0, then −

    • if count mod 4 is same as 0, then −

      • direction := "N"

    • otherwise when count mod 4 is same as 1, then −

      • direction := "E"

    • otherwise when count mod 4 is same as 2, then −

      • direction := "S"

    • otherwise when count mod 4 is same as 3, then −

      • direction := "W"

  • if count < 0, then −

    • if count mod 4 is same as 0, then −

      • direction := "N"

    • otherwise when count mod 4 is same as -1, then −

      • direction := "W"

    • otherwise when count mod 4 is same as -2, then −

      • direction := "S"

    • therwise when count mod 4 is same as -3, then −

      • direction := "E"

  • return direction

Example 

Let us see the following implementation to get better understanding −

 Live Demo

#include<bits/stdc++.h>
using namespace std;
string get_dir(string s) {
   int count = 0;
   string direction = "";
   for (int i = 0; i < s.length(); i++){
      if (s[0] == '\n')
         return NULL;
      if (s[i] == 'L')
         count--;
      else
         count++;
   }
   if (count > 0){
      if (count % 4 == 0)
         direction = "N";
      else if (count % 4 == 1)
         direction = "E";
      else if (count % 4 == 2)
         direction = "S";
      else if (count % 4 == 3)
         direction = "W";
   }
   if (count < 0){
      if (count % 4 == 0)
         direction = "N";
      else if (count % 4 == -1)
         direction = "W";
      else if (count % 4 == -2)
         direction = "S";
      else if (count % 4 == -3)
         direction = "E";
   }
   return direction;
}
int main() {
   string s = "RRLRLLR";
   cout << (get_dir(s));
}

Input

"RRLRLLR"

Output

E

Updated on: 19-Aug-2020

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements