Advertisement
Guest User

Untitled

a guest
Apr 5th, 2013
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var monotone = {
  2.     // 2D cross product of OA and OB vectors, i.e. z-component of their 3D cross product.
  3.     // Returns a positive value, if OAB makes a counter-clockwise turn,
  4.     // negative for clockwise turn, and zero if the points are collinea    
  5.     cross: function(o, a, b) {
  6.         return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  7.     },
  8.  
  9.     convex_hull: function(points) {
  10.         // Boring case: no points or a single point, possibly repeated multiple times.
  11.         if (points.length <= 3)
  12.             return false;
  13.  
  14.         // Build lower hull
  15.         var lower = [], p;
  16.         for (p in points) {
  17.             while (lower.length >= 2 && this.cross(lower[lower.length - 2], lower[lower.length - 1], points[p]) <= 0)
  18.                 lower.pop();
  19.             lower.push(points[p]);
  20.         }
  21.  
  22.         // Build upper hull
  23.         var upper = [];
  24.         for (p in points.reverse()) {
  25.             while (upper.length >= 2 && this.cross(upper[upper.length - 2], upper[upper.length - 1], points[p]) <= 0)
  26.                 upper.pop();
  27.             upper.push(points[p]);
  28.         }
  29.  
  30.         // Concatenation of the lower and upper hulls gives the convex hull.
  31.         // Last point of each list is omitted because it is repeated at the beginning of the other list.
  32.         upper.pop();
  33.         lower.pop();
  34.         var ret = [];
  35.         for (p in lower)
  36.             ret.push(lower[p]);
  37.         for (p in upper)
  38.             ret.push(upper[p]);
  39.  
  40.         return ret;
  41.     }
  42. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement