Advertisement
Guest User

Untitled

a guest
Apr 18th, 2014
38
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.58 KB | None | 0 0
  1. public class ConvexHull {
  2.     public static double orientation(Point p1, Point p2, Point p3) {
  3.         double val;
  4.         //p1=p l p2=q l p3 = r
  5.         //val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  6.         //val = -p2.x*p1.y + p3.x*p1.y + p1.x*p2.y - p3.x*p2.y - p1.x*p3.y + p2.x*p3.y;
  7.         val = (p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y);
  8.         return val;
  9.        
  10.         /*
  11.         // orientation is to the left-hand side
  12.         if (val > 0)
  13.             return -1;
  14.        
  15.         // orientation is to the right-hand side
  16.         if (val < 0)
  17.             return 1;  
  18.        
  19.         // orientation is neutral
  20.         return 0;*/
  21.     }
  22.    
  23.     public static Point[] giftWrap(Point[] pointSet) {
  24.         if (pointSet.length < 3){
  25.             return pointSet;
  26.         }
  27.  
  28.         // Find the leftmost point
  29.         int l = 0;
  30.         for (int i = 1; i < pointSet.length; i++) {
  31.             if (pointSet[i].x < pointSet[l].x){
  32.                 l = i;
  33.             }
  34.         }
  35.         Point pointOnHull = pointSet[l];
  36.  
  37.         Point[] hull = new Point[pointSet.length];
  38.         Point endPoint;
  39.         int len = 0;
  40.         do {
  41.             hull[len] = pointOnHull;
  42.             endPoint = pointSet[0];
  43.             for (int i = 1; i < pointSet.length; i++){
  44.                 if ((endPoint == pointOnHull) || (orientation(pointOnHull, endPoint, pointSet[i]) > 0)){
  45.                     endPoint = pointSet[i];
  46.                 }
  47.             }
  48.             len++;
  49.             pointOnHull = endPoint;
  50.         } while (endPoint != hull[0]);
  51.        
  52.         Point[] result = new Point[len];
  53.         for(int i = 0; i < len; i++){
  54.             result[i] = hull[i];
  55.         }
  56.         return result;
  57.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement