Search code examples
algorithmmathgeometrycoordinate-systemscoordinate

Algorithm to join 4 co-ordinates such that it always results in a quadilateral


We're given the coordinates of 4 points on the 2D plane. How can we find an order to join them with lines to form a quadilateral (whenever it's possible)?


Solution

  • A few stages, assuming the end result needs to be 4 couples of points (and/or the equation of the line between them):

    1. Take any three points, and make a triangle.
    2. If the forth point is inside the traingle, swap it with ny of the three.
    3. Having only the last point left, calculate which two point you want to attach it to. This is done by playing with the line eqations and finding where the intersecting points are. Clarification below.
    4. Return two sides of the triangle + the 2 lines between the forth point and the ones you chose from stage 2.

    Step 2 clarification:
    Let us say that point A is not in the triangle (which is BCD). Every line devides the plain into two sides. we want to find the point (B, C or D) s.t. the line between it and A runs between the other two (they are on opposite sides of the line). This is the point we DO NOT want to attach to A.

    Example: Given A(0,0), B(10,0), C(10,10) and D(0,10). We have the triangle BCD. The line BC leaves A & D on the same side of the plain. So does DC. The line AC leaves B & D on opposite sides of the plain - so we want to connect A to B & C.