Write a function to tell if two line segments intersect or not.
Anonymous
This is my approach: 1. Get the slope of the two lines m1, and m2 2. If they are equal means they are parallel and return false 3. else compute b1, and b2 such that the first line equation is y = m1x+b1 and the second line equation y = m2x+b2 4. Compute the intersection point X, Y such that m1x+b1 = m2x+b2 this will lead us to finding x and then y 5. Check in the first line and the second line SEGMENTS that they include this point .. bool check(line l, point p) { double mnX = min(l.p1.x, l.p2.x); double mxX = max(l.p1.x, l.p2.x); if(!(mnX <= p.x && p.x <= mxX)) return false; return true; } bool lines_intersect(line l1, line l2) { double m1 = (l1.p1.y-l1.p2.y)/(l1.p1.x-l1.p2.x); double m2 = (l2.p1.y-l2.p2.y)/(l2.p1.x-l2.p2.x); if(fabs(m1-m2) <= 1e-9) return false; double b1 = l1.p1.y-(l1.p1.x)*m1; double b2 = l2.p1.y-(l2.p1.x)*m2; double intersectionX = (b1*-1+b2)/(m1-m2); double intersectionY = m1*intersectionX+b1; cout << intersectionX << " " << intersectionY << endl; if(check(l1, point(intersectionX, intersectionY)) && check(l2, point(intersectionX, intersectionY))) return true; return false; }
Check out your Company Bowl for anonymous work chats.