Saturday, January 21, 2012

Finds the intersection point of two lines or two segments

#include <iostream>


#define min(a, b)(a>b?b:a)
#define max(a, b)(a>b?a:b)


typedef struct
{
    double x, y;
}pp;


pp A, B, C, D;


int main()
{
    double a1, b1, c1, a2, b2, c2;
    while(1)
    {
        printf("Enter the points A, B, C, and D\n");
        scanf("%lf %lf %lf %lf %lf %lf %lf %lf", &A.x, &A.y, &B.x, &B.y, &C.x, &C.y, &D.x, &D.y);


        /*A = y2-y1
        B = x1-x2
        C = A*x1+B*y1*/


        a1 = B.y - A.y;
        b1 = A.x - B.x;
        c1 = a1*A.x+b1*A.y;


        a2 = D.y - C.y;
        b2 = C.x - D.x;
        c2 = a2*C.x+b2*C.y;


        /*double det = A1*B2 - A2*B1
    if(det == 0){
        //Lines are parallel
    }else{
        double x = (B2*C1 - B1*C2)/det
        double y = (A1*C2 - A2*C1)/det
    }*/


        double det, xx, yy;


        det = a1*b2 - a2*b1;


        if(det == 0)
        {
            printf("AB and CD Lines are Parallel\n");
        }
        else
        {
            xx = (b2*c1 - b1*c2)/det;
            yy = (a1*c2 - a2*c1)/det;


            printf("The Intersection Point of AB and CD (line) is (x, y) = (%lf, %lf)\n", xx, yy);


            if( ( (min(A.x, B.x) <= xx && xx <= max(A.x, B.x)) && (min(A.y, B.y) <= yy && yy <= max(A.y, B.y)) )
            && ( (min(C.x, D.x) <= xx && xx <= max(C.x, D.x)) && (min(C.y, D.y) <= yy && yy <= max(C.y, D.y)) ) )


                printf("The Intersection Point of AB and CD (segment) is (x, y) = (%lf, %lf)\n", xx, yy);
            else
                printf("The segments AB and CD does not intersect\n", xx, yy);
        }
    }
    return 0;
}

No comments:

Post a Comment