- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
C++ program to find the best fit rectangle that covers a given point
In this article, we will be discussing a program to find the best fit rectangle that covers a given point.
In this problem, we are given we the coordinates of a point (x,y) and a ratio of length/breadth = l/b (say). We have to find the coordinates of a rectangle which contains the given point and whose dimensions follow the given ratio. In case of multiple rectangle existing, we have to choose the one having the shortest distance between its euclid’s center and the given point.
To solve this, first we would minimize the ratio l/b. After that, we find the min(n/l,m/b) value to stay in the (n,m) region (allowed 2d space). Firstly, let us suppose that (x,y) is the center of our rectangle only. If its not, we would find the original coordinates by simultaneously subtracting and adding the values of the length and breadth respectively.
Example
#include <cmath> #include <iostream> using namespace std; //to minimize the value of given ratio int greatest_div(int l, int b) { if (l == 0) return b; else return greatest_div(b % l, l); } //to calculate the coordinates void calc_coordinates(int n, int m, int x, int y, int l, int b) { int k, div1; int x1, y1, x2, y2; div1 = greatest_div(l, b); l /= div1; b /= div1; k = min(n / l, m / b); //finding the range in which the given point exists x1 = x - (k * l - k * l / 2); x2 = x + k * l / 2; y1 = y - (k * b - k * b / 2); y2 = y + k * b / 2; //if the coordinates go out of the range if (x1 < 0){ x2 -= x1; x1 = 0; } if (x2 > n){ x1 -= x2 - n; x2 = n; } if (y1 < 0){ y2 -= y1; y1 = 0; } if (y2 > m) { y1 -= y2 - m; y2 = m; } cout << "Coordinates : " << x1 << " " << y1 << " " << x2<< " " << y2 << endl; } int main() { int n = 50, m = 20, x = 10, y = 6, l = 4, b = 7; calc_coordinates(n, m, x, y, l, b); return 0; }
Output
Coordinates : 6 0 14 14