Advertisement
Guest User

Untitled

a guest
Mar 1st, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Comparator;
  3.  
  4. public class Polygon
  5. {
  6.    
  7.     int ncorners = 0;
  8.     Point[] points;
  9.    /**
  10.       Constructs a Polygon object with no corners
  11.    */
  12.    public Polygon()
  13.    {
  14.        points = new Point[0];
  15.    }
  16.    
  17.    /**
  18.       Adds a point to the list.
  19.       @param p the point to add
  20.    */
  21.    public void add(Point p)
  22.    {
  23.        points = addToArray(points, p);
  24.        ncorners++;
  25.    }
  26.    
  27.    /**
  28.       Computes the area of a polygon.
  29.       @return area of a polygon
  30.    */
  31.    public double getArea()
  32.    {
  33.       if (ncorners < 3) return 0;
  34.       if (ncorners == 3) {
  35.           return getTriangleSize(points);
  36.       }else {
  37.  
  38.           Arrays.sort(points, new Comparator<Point>() {
  39.               public int compare(Point a, Point b) {
  40.                   if(a.getX() > b.getX()) {
  41.                       return 1;
  42.                   }else if(a.getX() < b.getX()) {
  43.                       return -1;
  44.                   }else {
  45.                       return 0;
  46.                   }
  47.               }
  48.           });
  49.          
  50.           Point[] triangle = new Point[]{points[points.length -1], points[points.length -2], points[points.length -3]};
  51.          
  52.           Polygon p = new Polygon();
  53.           for(int i = 0; i < (points.length - 1); i++) {
  54.               p.add(points[i]);
  55.           }
  56.  
  57.           return getTriangleSize(triangle) + p.getArea();
  58.  
  59.       }
  60.    }
  61.    
  62.    private double getTriangleSize(Point[] pointArray) {
  63.        
  64.        //Just making the triangle calculation algorithm easier to type.
  65.        double x1 = pointArray[0].getX();
  66.        double y1 = pointArray[0].getY();
  67.        double x2 = pointArray[1].getX();
  68.        double y2 = pointArray[1].getY();
  69.        double x3 = pointArray[2].getX();
  70.        double y3 = pointArray[2].getY();
  71.        
  72.        //Algorithm provided by assignment.
  73.        return ((x1*y2) + (x2*y3) + (x3*y1) - (y1*x2) - (y2*x3) - (y3*x1)) / 2;
  74.    }
  75.    
  76.    private Point[] addToArray(Point[] array, Point newPoint) {
  77.        Point[] point = new Point[array.length + 1];
  78.        for(int i = 0 ; i < array.length; i++) {
  79.            point[i] = array[i];
  80.        }
  81.        point[point.length-1] = newPoint;
  82.        return point;
  83.    }
  84.    
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement