解説は他記事で詳しいのがあるので割愛します。
- P1P2とP1P3の外積とP1P2とP1P4の外積の積が負
- P3P4とP3P1の外積とP3P4とP3P2の外積の積が負
を用いて判定しています。
コードは以下
// 線分p1p2とp3p4が交わるかどうかを判定する
fn intersect(p1: (i64, i64), p2: (i64, i64), p3: (i64, i64), p4: (i64, i64)) -> bool {
outer_product(p1, p2, p3) * outer_product(p1, p2, p4) < 0
&& outer_product(p3, p4, p1) * outer_product(p3, p4, p2) < 0
}
// p1p2とp1p3の外積
fn outer_product(p1: (i64, i64), p2: (i64, i64), p3: (i64, i64)) -> i64 {
let a = p2.0 - p1.0;
let b = p2.1 - p1.1;
let c = p3.0 - p1.0;
let d = p3.1 - p1.1;
a * d - b * c
}