ปัญหา
ได้รับพิกัดของรูปหลายเหลี่ยม ตรวจสอบว่าเป็นรูปทรง Equable หรือไม่ (เส้นรอบรูป = พื้นที่)
ตัวอย่าง
อินพุต: polygon[][] = {{0,0}, {5,7}, {2,0}}
เอาต์พุต: Not equable
คำอธิบาย: เส้นรอบรูป ≈ 18.21, พื้นที่ = 7
แนวทางแก้ปัญหา
คำนวณพื้นที่และเส้นรอบรูปจากพิกัด แล้วเปรียบเทียบ
- เส้นรอบรูป: ผลรวมระยะทางระหว่างจุดติดกัน
- พื้นที่ (Shoelace Formula): ½|Σ(xᵢyᵢ₊₁ - xᵢ₊₁yᵢ)|
โปรแกรมตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
double findShapeArea(double cord[][2], int n) {
double area = 0.0;
int j = n - 1;
for (int i = 0; i < n; i++) {
area += (cord[j][0] + cord[i][0]) * (cord[j][1] - cord[i][1]);
j = i;
}
return abs(area / 2.0);
}
double findShapePerimeter(double cord[][2], int n) {
double perimeter = 0.0;
int j = n - 1;
for (int i = 0; i < n; i++) {
perimeter += sqrt(pow(cord[j][0] - cord[i][0], 2) +
pow(cord[j][1] - cord[i][1], 2));
j = i;
}
return perimeter;
}
int isEquableShape(double cord[][2], int n) {
double area = findShapeArea(cord, n);
double peri = findShapePerimeter(cord, n);
cout << "Area: " << area << ", Perimeter: " << peri << endl;
return (abs(area - peri) < 1e-9); // เปรียบเทียบ float
}
int main() {
int n = 3;
double cord[3][2] = {{0,0}, {5,7}, {2,0}};
if (isEquableShape(cord, n))
cout << "The given shape is an equable shape";
else
cout << "The given shape is not an equable shape";
return 0;
}
ผลลัพธ์
Area: 7, Perimeter: 18.21 The given shape is not an equable shape