Skip to content

Instantly share code, notes, and snippets.

@mbalunovic
Created March 1, 2009 08:09
Show Gist options
  • Save mbalunovic/72267 to your computer and use it in GitHub Desktop.
Save mbalunovic/72267 to your computer and use it in GitHub Desktop.
line segments intersection
#include <cstdio>
#include <algorithm>
#include <cmath>
using namespace std;
struct point {
double x,y;
point ( double x = 0, double y = 0 ) : x(x),y(y) {}
};
struct line {
point p1,p2;
void read (){
scanf("%lf %lf %lf %lf",&p1.x,&p1.y,&p2.x,&p2.y);
}
};
double dx1,dy1,dx2,dy2;
double s,t;
point in;
void intersection ( line a, line b ){
dx1 = a.p2.x - a.p1.x;
dy1 = a.p2.y - a.p1.y;
dx2 = b.p2.x - b.p1.x;
dy2 = b.p2.y - b.p1.y;
if ( fabs ( dx2 * dy1 - dx1 * dy2 ) < 0.0000001 ){
printf("Paralelni\n");
return;
}
s = (dx1 * (b.p1.y - a.p1.y) + dy1 * (a.p1.x - b.p1.x)) / double( dx2 * dy1 - dx1 * dy2 );
t = (dx2 * (a.p1.y - b.p1.y) + dy2 * (b.p1.x - a.p1.x)) / double( dx1 * dy2 - dx2 * dy1 );
if ( s<0 || s>1 || t<0 || t>1 )
printf("Nemaju presjeka\n");
else {
in = point (a.p1.x + t * dx1, a.p1.y + t * dy1);
printf("%lf %lf\n",in.x,in.y);
}
}
line a,b;
int main(){
a.read();
b.read();
intersection ( a,b );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment