ในระนาบ 2d จะได้รับสี่จุด อัลกอริทึมนี้จะตรวจสอบว่าจุดสี่จุดกำลังก่อตัวเป็นสี่เหลี่ยมจัตุรัสหรือไม่
การหากำลังสองเราต้องตรงกับเงื่อนไขเหล่านี้ -
- ทั้งสี่ด้านที่เกิดขึ้นจากคะแนนที่กำหนดเหมือนกัน
- ด้านที่เชื่อมต่อกันทั้ง 2 ด้านเป็นมุมฉาก
อินพุตและเอาต์พุต
Input:
Four points {(20, 10), (10, 20), (20, 20), (10, 10)}
Output:
Points are forming a square. อัลกอริทึม
isFormingSquare(p1, p2, p3, p4)
ในขั้นตอนนี้ เราจะใช้เมธอด squareDist(p1, p2) ซึ่งจะคืนค่าระยะกำลังสองของจุดที่กำหนดสองจุด
ป้อนข้อมูล: สี่แต้ม
ผลลัพธ์: จริงเมื่อแต้มกลายเป็นสี่เหลี่ยมจัตุรัส
Begin dist12 := squareDist(p1, p2) dist13 := squareDist(p1, p3) dist14 := squareDist(p1, p4) if dist12 = dist13 and 2*dist12 = dist14, then dist := squareDist(p2, p4) return true when dist = squareDist(p3, p4) and dist = dist12 if dist13 = dist14 and 2*dist13 = dist12, then dist := squareDist(p2, p3) return true when dist = squareDist(p2, p4) and dist = dist13 if dist12 = dist14 and 2*dist12 = dist13, then dist := squareDist(p2, p3) return true when dist = squareDist(p3, p4) and dist = dist12 return false End
ตัวอย่าง
#include<iostream>
using namespace std;
struct Point {
int x, y;
};
int squareDist(Point p, Point q) {
return (p.x - q.x)*(p.x - q.x) + (p.y - q.y)*(p.y - q.y);
}
bool isSquare(Point p1, Point p2, Point p3, Point p4) { //check four points are forming square or not
int dist12 = squareDist(p1, p2); // distance from p1 to p2
int dist13 = squareDist(p1, p3); // distance from p1 to p3
int dist14 = squareDist(p1, p4); // distance from p1 to p4
//when length of p1-p2 and p1-p3 are same, and square of (p1-p4) = 2*(p1-p2)
if (dist12 == dist13 && 2*dist12 == dist14) {
int dist = squareDist(p2, p4);
return (dist == squareDist(p3, p4) && dist == dist12);
}
//same condition for all other combinations
if (dist13 == dist14 && 2*dist13 == dist12) {
int dist = squareDist(p2, p3);
return (dist == squareDist(p2, p4) && dist == dist13);
}
if (dist12 == dist14 && 2*dist12 == dist13) {
int dist = squareDist(p2, p3);
return (dist == squareDist(p3, p4) && dist == dist12);
}
return false;
}
int main() {
Point p1 = {20, 10}, p2 = {10, 20}, p3 = {20, 20}, p4 = {10, 10};
if(isSquare(p1, p2, p3, p4))
cout << "Points are forming a square.";
else
cout << "Points are not forming a square";
} ผลลัพธ์
Points are forming a square.