查詢最佳契合且覆蓋給定點的矩形的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