# Intersection

16.3 Intersection: Given two straight line segments (represented as a start point and an end point), compute the point of intersection, if any.
inline void pause()
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
pair<double, double> intersection(pair<int, int> one, pair<int, int> one1, pair<int, int> two, pair<int, int> two1) {
int diff_x1 = one.first - two.first;
int diff_x2 = one1.first - two1.first;
int diff_y1 = one.second - two.second;
int diff_y2 = one1.second - two1.second;
// intersection = one negative, but not both
if (!((diff_x1 <= 0 ^ diff_x2 <= 0) || (diff_y1 <= 0 ^ diff_y2 <= 0))) {
cout << "no intersection" << endl;
}
pair<double, double> intersection;
// m = y2-y1/x2-x1
double slope1 = (one1.second - one.second) / (one1.first - one.first);
double slope2 = (two1.second - two.second) / (two1.first - two.first);
// b = y - mx
double y_int1 = one.second - slope1 * one.first;
double y_int2 = two.second - slope2 * two.first;
intersection.first = (y_int2 - y_int1) / (slope1 - slope2);
intersection.second = slope1 * intersection.first + y_int1;
// in order to an intersection to exist, the intersection point
// must exist within the domain and range defined by both line segments
if (!(intersection.first >= min(one.first, one1.first) && intersection.first <= max(one.first, one1.first) &&
intersection.first >= min(two.first, two1.first) && intersection.first <= max(two.first, two1.first) &&
intersection.second >= min(one.second, one1.second) && intersection.second <= max(one.second, one1.second) &&
intersection.second >= min(two.second, two1.second) && intersection.second <= max(two.second, two1.second))) {
cout << "no intersection" << endl;
}
return intersection;
}
int main()
{
pair<int, int> one, one1, two, two1;
one = { 1,1 };
one1 = {2,2};
two = {1,2};
two1 = { 2,1 };
pair<double, double> a = intersection(one, one1, two, two1);
cout << a.first << " " << a.second << endl;
pause();
one = { 0,0 };
one1 = { 3,3 };
two = { 1,0 };
two1 = { 2,1 };
a = intersection(one, one1, two, two1);
cout << a.first << " " << a.second << endl;
pause();
one = { 0,0 };
one1 = { 3,3 };
two = { 0,2 };
two1 = { 2,0 };
a = intersection(one, one1, two, two1);
cout << a.first << " " << a.second << endl;
pause();
one = { 0,0 };
one1 = { 3,3 };
two = { 3,0 };
two1 = { 2,1 };
a = intersection(one, one1, two, two1);
cout << a.first << " " << a.second << endl;
pause();
}