1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| #include <iostream>
struct Point { double x; double y; };
bool is_intersection(Point A, Point B, Point C, Point D) { double c1 = (B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x); double c2 = (B.x - A.x) * (D.y - A.y) - (B.y - A.y) * (D.x - A.x); double c3 = (D.x - C.x) * (A.y - C.y) - (D.y - C.y) * (A.x - C.x); double c4 = (D.x - C.x) * (B.y - C.y) - (D.y - C.y) * (B.x - C.x);
return c1 * c2 <= 0 && c3 * c4 <= 0; }
Point get_intersection(Point A, Point B, Point C, Point D) { double k1 = (B.y - A.y) / (B.x - A.x); double k2 = (D.y - C.y) / (D.x - C.x);
if (k1 == k2) { return {0, 0}; }
double b1 = A.y - k1 * A.x; double b2 = C.y - k2 * C.x;
double x = (b2 - b1) / (k1 - k2);
double y = k1 * x + b1;
return {x, y}; }
int main() { Point A = {0, 0}; Point B = {1, 1}; Point C = {1, 1}; Point D = {2, 4};
if (is_intersection(A, B, C, D)) { Point intersection = get_intersection(A, B, C, D); double x = intersection.x; double y = intersection.y; std::cout << "Intersection: (" << x << ", " << y << ")" << std::endl; } else { std::cout << "No intersection" << std::endl; } return 0; }
|