Check if possible to move from given coordinate to desired coordinate in C++

C++Server Side ProgrammingProgramming

Suppose we have two coordinates (sx, sy), and (tx, ty), we have to check whether we can move from starting point to ending point or not. Here we can move consists of taking a point (x, y) and transforming it to either (x, x+y) or (x+y, y).

So if the inputs are (1, 1) and (4,5), then the answer will be true, this is because move (1,1) to (2,1), then (3,1), then (4,1), then (4,5).

To solve this, we will follow these steps −

  • while tx > sx and ty > sy, do −
    • if tx > ty, then −
      • tx := tx mod ty
    • Otherwise
      • ty := ty mod tx
  • return (true when sx is same as tx AND sy <= ty AND (ty - sy) mod tx is same as 0) OR (sy is same as ty AND x >= sx AND (tx - sx) mod ty is 0)

Example (C++)

Let us see the following implementation to get better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
bool solve(int sx, int sy, int tx, int ty) {
   while(tx > sx && ty > sy){
      if(tx > ty){
         tx %= ty;
      }else ty %= tx;
   }
   return (sx == tx && sy <= ty && (ty - sy) % tx == 0) || (sy == ty && tx >= sx && (tx - sx) % ty == 0);
}
main(){
   cout << solve(1,1,4,5);
}

Input

1, 1, 4, 5

Output

1
raja
Published on 19-Jan-2021 09:57:46
Advertisements