2D 평면에서는 4개의 점이 제공됩니다. 이 알고리즘은 4개의 점이 정사각형을 형성하는지 여부를 확인합니다.
다음 조건과 일치해야 하는 사각형을 확인하는 중 -
- 주어진 점으로 이루어진 네 변은 모두 동일합니다.
- 연결하는 두 면이 모두 직각입니다.
입력 및 출력
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) 메서드를 사용하여 주어진 두 점의 거리 제곱을 반환합니다.
입력: 4점.
출력: 주어진 점이 정사각형을 형성할 때 참입니다.
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.