ในบทความนี้ เราจะพูดถึงโปรแกรมเพื่อค้นหาสี่เหลี่ยมที่พอดีที่สุดซึ่งครอบคลุมจุดที่กำหนด
ในปัญหานี้ เราได้รับพิกัดของจุด (x,y) และอัตราส่วนของความยาว/ความกว้าง =l/b (พูด) เราต้องหาพิกัดของสี่เหลี่ยมผืนผ้าที่มีจุดที่กำหนดและมีขนาดตามอัตราส่วนที่กำหนด ในกรณีของสี่เหลี่ยมที่มีอยู่หลายอัน เราต้องเลือกอันที่มีระยะห่างระหว่างจุดศูนย์กลางของยูคลิดกับจุดที่กำหนดสั้นที่สุด
ในการแก้ปัญหานี้ ก่อนอื่นเราจะลดอัตราส่วน l/b ให้เหลือน้อยที่สุด หลังจากนั้น เราจะหาค่า min(n/l,m/b) ที่จะอยู่ในขอบเขต (n,m) (อนุญาตช่องว่าง 2d) ประการแรก สมมุติว่า (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