Mar 15, 2022

Check if 2 line segments intersect and find point of intersection

 #include <iostream>

using namespace std;


// Given two straight line segments (represented as a start point and an end point),

// compute the point of intersection, if any.


//Logic - To be able to intersect the slopes should be opposite

bool doIntersect(int sx, int sy, int ex, int ey, int s1x, int s1y, int e1x, int e1y)

{

    float slope1 = (sy-s1y)/(sx-s1x);

    float slope2 = (e1y-sy)/(e1x-sx);

    float slope3 = (ey-s1y)/(ex-s1x);

    float slope4 = (e1y-ey)/(e1x-ex);

    

    if(slope1>=slope2 && slope3>=slope4)

        return false;

    if(slope1>=slope2 && slope3<=slope4)

        return true;

    if(slope1<=slope2 && slope3<=slope4)

        return false;

    if(slope1<=slope2 && slope3>=slope4)

        return true;


    

}


//point of intersect can be computed using slope formula

//say Ix. Iy is the intersection then slope(S,I) = slope(I,E) and slope(S1,I) = slope(I,E1)

//This will generate 2 equations with 2 unknowns and hence can be solved.

//special cases should be checked where either segments start or end lie on the other. In that case

// the distance formula can be used to verify.


int main() {

// your code goes here

bool res = doIntersect(1,2,3,4,2,6,2,-8);

if(res)

    cout << "intersect";

else

    cout << "don't intersect";

return 0;

}