-1

I am trying to make a program that makes the user input a pairs of xy coordinates. The program must use the three farthest points from (0,0) as the vertices of the triangle. The program must output the area of the triangle. I know the formula for it but i am having trouble in getting the three farthest points from (0,0).

Here I have the code for sorting only the x coordinates in ascending order. How do I sort the pairs and get the three farthest points? Or is there any better way to make this program?

int main() {
    int x, a, b, t;
    cin >> a; // a pairs of x and y
    int xcoor[a], ycoor[a];
    for (x = 1; x <= a; x++)
    {
        //enter coordinates
        cin >> xcoor[x] >> ycoor[x];
    }
    for (x = 0; x < a; x++)
    {
        for (int y = 0; y < a - 1; y++)
        {
            if (xcoor[y] > xcoor[y + 1])
            {
                t = xcoor[y];
                xcoor[y] = xcoor[y + 1];
                xcoor[y + 1] = t;
            }
        }
    }
    return 0;
}

2 Answers2

0

You can define a struct Point that defines a coordinate instead of having two separated variables.

With an operator< on points expressing the distance from the center, you can use std::sort to sort arrays/vectors of Point.

Something like:

struct Point {
  int x, y;

  bool operator<(const Point& src) const
    { return x*x + y*y < src.x*src.x + src.y*src.y; // or anything else
    }
};

int main() {
    int x,a,b,t;
    cin>>a; // a pairs of x and y
    Point point[a]; // be careful, it is a gcc extension since a is not a compilation constant
    for (x=0; x<a; x++) // be careful, arrays in C/C++ starts from 0!
    {
    //enter coordinates
    cin>>point[x].x>>point[x].y;
    }
    std::sort(&point[0], &point[a]);
    return 0;
}

helps you to find the three farthest points.

Franck
  • 1,635
  • 1
  • 8
  • 11
0

One way is to find the convex hull of those points, the furthest points are the vertices of that convex hull, take the furthest 3 of the vertices.

This is one way to find the convex hull of a set of points.

You can also check this, it may help you find your way in solving your problem.

Community
  • 1
  • 1
Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36