Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Created June 24, 2018 12:32
Show Gist options
  • Select an option

  • Save thomasnield/e702924f90459763155bebb1a39dd3f6 to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/e702924f90459763155bebb1a39dd3f6 to your computer and use it in GitHub Desktop.
Segment Intersection
// https://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/
fun main(args: Array<String>) {
val x1 = Point(0.0, 0.0)
val y1 = Point(4.0, 4.0)
val x2 = Point(0.0, 4.0)
val y2 = Point(4.0, 0.0)
println(intersect(x1,y1,x2,y2))
}
data class Point(val x: Double, val y: Double)
data class Segment(val start: Point, val end: Point)
fun ccw(a: Point, b: Point, c: Point) =
(c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x)
fun intersect(x1: Point, y1: Point, x2: Point, y2: Point) =
ccw(x1,x2,y2) != ccw(y1,x2,y2) && ccw(x1,y1,x2) != ccw(x1,y1,y2)
fun intersect(segment1: Segment, segment2: Segment) =
intersect(segment1.start, segment1.end, segment2.start, segment2.end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment