Skip to content

Instantly share code, notes, and snippets.

@WinnerOK
Created December 7, 2019 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WinnerOK/abaf0b1eab692366b4bd9682d5291b1d to your computer and use it in GitHub Desktop.
Save WinnerOK/abaf0b1eab692366b4bd9682d5291b1d to your computer and use it in GitHub Desktop.
Find out wheter segments AB CD intersect
type point struct {
x int
y int
}
func pointSum(p1, p2 point) point {
return point{
x: p1.x + p2.x,
y: p1.y + p2.y,
}
}
type lineSegment struct {
begin point
end point
}
func isCounterClockwiseListed(A, B, C point) bool {
// 3 points are listed ccw iff slope AB < AC
// Slope AB = (B_y-A_y)/(B_x-A_x)
return (B.y-A.y)*(C.x-A.x) < (C.y-A.y)*(B.x-A.x)
}
func doSegmentsIntersect(s1, s2 lineSegment) bool {
// 2 segments AB CD intersect iff A and B separated by CD & C and D separated by AB
// if A and B separated by CD, then ACD and BCD should have different orientation
A := s1.begin
B := s1.end
C := s2.begin
D := s2.end
return isCounterClockwiseListed(A, C, D) != isCounterClockwiseListed(B, C, D) &&
isCounterClockwiseListed(A, B, C) != isCounterClockwiseListed(A, B, D)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment