#include <stdio.h>
struct point {
double x;
double y;
};
struct line {
struct point p1;
struct point p2;
};
/* 二つの線分が交差する時, 真を返す */
int intersects(struct line l1, struct line l2){
int result;
double a, b;
double p;
double x, y;
p = (l1.p1.y-l1.p2.y)*(l2.p1.x-l2.p2.x) -
(l1.p1.x-l1.p2.x)*(l2.p1.y-l2.p2.y);
/* printf("p: %le\n", p); */
if(p == 0.0){
result = 0;
} else {
a = ((l2.p1.x-l2.p2.x)*(l2.p2.y-l1.p2.y) -
(l2.p1.y-l2.p2.y)*(l2.p2.x-l1.p2.x)) / p;
b = ((l1.p1.y-l1.p2.y)*(l1.p2.x-l2.p2.x) -
(l1.p1.x-l1.p2.x)*(l1.p2.y-l2.p2.y)) / p;
/* printf("a: %le b: %le\n", a, b); */
if((0.0 <= a) && (a <= 1.0) &&
(0.0 <= b) && (b <= 1.0)){
result = 1;
} else {
result = 0;
}
}
/* printf("\n"); */
return result;
}
int main(void){
struct line l1 = {{0.0, 1.0}, {1.0, 0.0}, };
struct line l2 = {{0.0, 0.0}, {1.0, 1.0}};
struct line l3 = {{0.0, 2.0}, {1.0, 2.0}};
struct line l4 = {{0.0, 1.0}, {1.0, 2.0}};
struct line l5 = {{1.0, 1.0}, {0.0, 1.0}, };
printf("for l1, l2: %d\n", intersects(l1, l2));
printf("for l1, l3: %d\n", intersects(l1, l3));
printf("for l2, l4: %d\n", intersects(l2, l4));
printf("for l2, l5: %d\n", intersects(l2, l5));
return 0;
}