Advertisement
jules0707

PointSET

Nov 9th, 2020
932
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.12 KB | None | 0 0
  1. import edu.princeton.cs.algs4.Point2D;
  2. import edu.princeton.cs.algs4.RectHV;
  3. import edu.princeton.cs.algs4.SET;
  4.  
  5.  
  6. public class PointSET {
  7.  
  8.     private SET<Point2D> pointsBST;
  9.  
  10.     // Construct an empty set of points
  11.     public PointSET() {
  12.         pointsBST = new SET<>();
  13.     }
  14.  
  15.     public boolean isEmpty() {
  16.         return pointsBST.isEmpty();
  17.     }
  18.  
  19.     // number of points in the set
  20.     public int size() {
  21.         return pointsBST.size();
  22.     }
  23.  
  24.     // Add the point to the set (if it is not already in the set)
  25.     public void insert(Point2D p) {
  26.         if (null == p) throw new IllegalArgumentException();
  27.         if (!pointsBST.contains(p)) {
  28.             pointsBST.add(p);
  29.         }
  30.     }
  31.  
  32.     //does the set contain point p?
  33.     public boolean contains(Point2D p) {
  34.         if (null == p) throw new IllegalArgumentException();
  35.         return pointsBST.contains(p);
  36.     }
  37.  
  38.     // draw all points to standard draw
  39.     public void draw() {
  40.         pointsBST.forEach(point2D -> point2D.draw());
  41.     }
  42.  
  43.     // all points that are inside the rectangle (or on the boundary)
  44.     public Iterable<Point2D> range(RectHV rect) {
  45.         if (null == rect) throw new IllegalArgumentException();
  46.         SET<Point2D> rangePoints = new SET<>();
  47.  
  48.         for (Point2D point2D : pointsBST) {
  49.             if (rect.contains(point2D)) rangePoints.add(point2D);
  50.         }
  51.         return rangePoints;
  52.     }
  53.  
  54.     // a nearest neighbor in the set to point p; null if the set is empty
  55.     public Point2D nearest(Point2D p) {
  56.         if (null == p) throw new IllegalArgumentException();
  57.  
  58.         if (pointsBST.isEmpty()) {
  59.             return null;
  60.         } else {
  61.             // any point in the SET will be a starting point champion
  62.             Point2D championPoint = pointsBST.iterator().next();
  63.  
  64.             for (Point2D point2D : pointsBST) {
  65.                 if (point2D.distanceSquaredTo(p) < championPoint.distanceSquaredTo(p)) {
  66.                     // we have a new champion
  67.                     championPoint = point2D;
  68.                 }
  69.             }
  70.             return championPoint;
  71.         }
  72.     }
  73. }
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement