Тест на выпуклость многоугольника.

Пример 1:

Многоугольник задан координатами своих вершин. Определите, является ли данный многоугольник выпуклым.

Решение от преподавателя:

#include
#include
using namespace std;
class Line {
public:
static int HowManyLines(){
return number_of_lines;
}

Line(double x1, double y1, double x2, double y2){
A = y1 - y2;
B = x2 - x1;
C = x1*y2 - x2*y1;

number_of_lines++;
}
int CheckPoint(double x, double y){
double t = A*x+B*y+C;
if (t == 0)
return 0;
if (t > 0)
return 1;
if (t < 0)
return -1;
return 666;
}
private:
double A, B, C;
static int number_of_lines;
};

int Line::number_of_lines = 0;
class Polygon {
public:
Polygon(double* x, double* y, int n){
this->x = x;
this->y = y;
this->n = n;
}
int CountSides(){
return n;
}
void GetSide(int n, double &x1, double &y1, double &x2, double &y2){
x1 = x[n];
y1 = y[n];
if(n < this->n-1){
x2 = x[n+1];
y2 = y[n+1];
}
else {
x2 = x[0];
y2 = y[0];
}
}
void GetPoint(int n, double &x, double &y) {
x = this->x[n];
y = this->y[n];
}
static bool IsConvex(Polygon* P) {
for (int i=0; i < P->CountSides(); i++) {
double current_sidex1, current_sidex2, current_sidey1, current_sidey2;
P->GetSide(i,current_sidex1, current_sidey1, current_sidex2, current_sidey2);
Line* l = new Line(current_sidex1, current_sidey1, current_sidex2, current_sidey2);
int sum = 0;
for(int j=0;jCountSides();j++) {
double cur_point_x, cur_point_y;
P->GetPoint(j,cur_point_x, cur_point_y);
if((cur_point_x == current_sidex1 && cur_point_y == current_sidey1)
||(cur_point_x == current_sidex2 && cur_point_y == current_sidey2))
continue;

sum += l->CheckPoint(cur_point_x, cur_point_y);
}
if(abs(sum) != P->CountSides()-2)
return false;
}
return true;
}
~Polygon() {
delete x;
delete y;
}
private:
double* x;
double* y;
int n;
};

Polygon* ReadPolygon() {
int num;
cout << "Enter number of points: ";
cin >> num;
double *x_coord = new double[num];
double *y_coord = new double[num];

for (int i=0; i < num; i++)
{
cout << "Enter point #" << i << ": ";
cin >> x_coord[i] >> y_coord[i];

}
//Polygon *P = new Polygon(x_coord, y_coord, num);
//return P;
return new Polygon(x_coord, y_coord, num);
}

int main() {
//Ax + By + C = 0
// (x1, y1), (x2, y2)
// (y1-y2)x + (x2-x1)y + (x1y2 - x2y1) = 0
Polygon* P;
P = ReadPolygon();
bool conv = Polygon::IsConvex(P);

cout << (conv?"Convex":"Not convex") << endl;
cout << (Line::HowManyLines()) << endl;
system("pause");
return 0;
}

Не нашли нужного вам решения? Оставьте заявку и наши авторы быстро и качественно помогут вам с решением.
Оставить заявку
Работа вам нужна срочно. Не волнуйтесь, уложимся!

Заполните, пожалуйста, данные для автора:

  • 22423 авторов готовы помочь тебе.
  • 2402 онлайн