Skip to content

Instantly share code, notes, and snippets.

@tamland
Created February 10, 2014 13:59
Show Gist options
  • Select an option

  • Save tamland/8916429 to your computer and use it in GitHub Desktop.

Select an option

Save tamland/8916429 to your computer and use it in GitHub Desktop.
import scala.collection.mutable.ListBuffer
case class Point(x: Double, y: Double)
/** Compute the convex hull of given points. Returns vertices ordered ccw */
def convexHull(_points: Seq[Point]): Seq[Point] = {
val points = _points.sortBy(_.x)
val upper = halfHull(points)
val lower = halfHull(points.reverse)
upper.remove(0)
lower.remove(0)
upper ++: lower
}
def halfHull(points: Seq[Point]) = {
val upper = new ListBuffer[Point]()
for (p <- points) {
while (upper.size >= 2 && leftTurn(p, upper(0), upper(1))) {
upper.remove(0)
}
upper.prepend(p)
}
upper
}
def leftTurn(p1: Point, p2: Point, p3: Point) = {
val slope = (p2.x - p1.x) * (p3.y - p1.y) - (p2.y - p1.y) * (p3.x - p1.x)
val collinear = math.abs(slope) <= 1e-9
val leftTurn = slope < 0
collinear || leftTurn
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment