
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Possible Movement from Given to Desired Coordinate in C++
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
- if tx > ty, then −
- 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 −
#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
Advertisements