C++ Program to find out the moves to read a point from another point in a 2D plane

C++Server Side ProgrammingProgramming

Suppose, there are two points in a 2D plane a and b that have the coordinates (x1, y1) and (x2, y2) respectively. Currently, we are at point 'a' and we can move at a distance of 1 either vertically or horizontally. We move to point b from point a, then get back to point a, and we go to point b again. It is not allowed to move through the same points more than once except the points a and b. We have to find out the moves we will make in this whole trip, and output it. If we move right, we print 'R', 'L' if we move left, 'U' if we move up, and 'D' if we move down. One thing we have to note is that x2 > x1 and y2 > y1.

So, if the input is like x1 = 0, y1 = 1, x2 = 3, y2 = 4, then the output will be UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU

To solve this, we will follow these steps −

s := a blank string
for initialize i := 0, when i < y2 - y1, update (increase i by 1), do:
   add "U" at the end of s
for initialize i := 0, when i < x2 - x1, update (increase i by 1), do:
   add "R" at the end of s
for initialize i := 0, when i < y2 - y1, update (increase i by 1), do:
   add "D" at the end of s
for initialize i := 0, when i < x2 - x1, update (increase i by 1), do:
   add "L" at the end of s
   add "LU" at the end of s
for initialize i := 0, when i < y2 - y1, update (increase i by 1), do:
   add "U" at the end of s
for initialize i := 0, when i < x2 - x1, update (increase i by 1), do:
   add "R" at the end of s
   add "RD" at the end of s
   add "RD" at the end of s
for initialize i := 0, when i < y2 - y1, update (increase i by 1), do:
   add "D" at the end of s
for initialize i := 0, when i < x2 - x1, update (increase i by 1), do:
   add "L" at the end of s
   add "LU" at the end of s
return s

Example

Let us see the following implementation to get better understanding −

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

string solve(int x1, int y1, int x2, int y2){
   string s = "";
   for(int i = 0; i < y2 - y1; i++)
      s.append("U");
   for(int i = 0; i < x2 - x1; i++)
      s.append("R");
   for(int i = 0; i < y2 - y1; i++)
      s.append("D");
   for(int i = 0; i < x2 - x1; i++)
      s.append("L");
   s.append("LU");
   for(int i = 0; i < y2 - y1; i++)
      s.append("U");
   for(int i = 0; i < x2 - x1; i++)
      s.append("R");
      s.append("RD");
      s.append("RD");
   for(int i = 0; i < y2 - y1; i++)  
      s.append("D");
   for(int i = 0; i < x2 - x1; i++) s.append("L");
      s.append("LU");
   return s;
}
int main() {
   int x1 = 0, y1 = 1, x2 = 3, y2 = 4; cout<< solve(x1, y1, x2, y2);
   return 0;
}

Input

0, 1, 3, 4

Output

UUURRRDDDLLLLUUUURRRRDRDDDDLLLLU
raja
Updated on 02-Mar-2022 12:40:34

Advertisements