find me on
 
twitter del.icio.us
linkedin flickr
goodreads flixster
facebook aim
dopplr stackoverflow
tweets
 
del.icio.us
 
recent posts
 
history
 
May 2009
M T W T F S S
« Mar   Jun »
 123
45678910
11121314151617
18192021222324
25262728293031
 
jason.prado (@) gmail.com real tangible
 
Convex Hull Algorithm in Scala
 

I’ve decided to forreals learn Scala and forreals learn some computational geometry (I’ve been faking it at my job for a year now). I’m using Processing to draw pixels to the screen, and it turns out to be amazingly easy to access the Java library from Scala. My first algorithm was the naive implementation of convex hull generation (given a set of points, draw the tightest convex polygon possible that contains all points). This implementation runs in O(n^2) but I plan to reimplement it using the O(nlogn) algorithm that’s only slightly more complex.

I think graphics is an interesting example of combining functional and imperative aspects of Scala. The program is all about the side effect of putting pixels on the screen, but functional tools help me get there. Check out this method I used for testing:

  def drawLine(pts: List[Point2D]): Unit = {
      def drawLines(p1: Point2D, p2: Point2D) : Point2D = { line(p1.x, p1.y, p2.x, p2.y); p2 }
      pts.reduceLeft(drawLines);
  }

This is a little hacky but, in my opinion, fairly elegant. Reduce does the work of giving me consecutive pairs and then I use line() to draw to the screen.

I’ve put up all the code here.

You can leave a response, or trackback from your own site.

Leave a Reply