查找最佳契合且覆盖给定点的矩形的C++程序
本文将探讨一个寻找最佳契合且覆盖给定点的矩形的程序。
此问题提供了点的坐标 (x,y) 以及长度/宽度 = l/b(假设)的比率。我们必须找出包含给定点的矩形的坐标,并且其维度遵循给定的比率。在存在多个矩形的情况下,我们必须选择与其欧几里得中心和给定点之间距离最短的矩形。
为了解决这个问题,我们首先要将比率 l/b 最小化。之后,我们找到 min(n/l,m/b) 值,以停留在 (n,m) 区域(允许的二维空间)内。首先,假设 (x,y) 仅是我们矩形的中心。如果不是这种情况,我们将分别同时减去和加上长度和宽度的值,得出原始坐标。
示例
#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;
}输出
Coordinates : 6 0 14 14
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP