Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import edu.princeton.cs.algs4.Point2D;
- import edu.princeton.cs.algs4.RectHV;
- import edu.princeton.cs.algs4.SET;
- public class PointSET {
- private SET<Point2D> pointsBST;
- // Construct an empty set of points
- public PointSET() {
- pointsBST = new SET<>();
- }
- public boolean isEmpty() {
- return pointsBST.isEmpty();
- }
- // number of points in the set
- public int size() {
- return pointsBST.size();
- }
- // Add the point to the set (if it is not already in the set)
- public void insert(Point2D p) {
- if (null == p) throw new IllegalArgumentException();
- if (!pointsBST.contains(p)) {
- pointsBST.add(p);
- }
- }
- //does the set contain point p?
- public boolean contains(Point2D p) {
- if (null == p) throw new IllegalArgumentException();
- return pointsBST.contains(p);
- }
- // draw all points to standard draw
- public void draw() {
- pointsBST.forEach(point2D -> point2D.draw());
- }
- // all points that are inside the rectangle (or on the boundary)
- public Iterable<Point2D> range(RectHV rect) {
- if (null == rect) throw new IllegalArgumentException();
- SET<Point2D> rangePoints = new SET<>();
- for (Point2D point2D : pointsBST) {
- if (rect.contains(point2D)) rangePoints.add(point2D);
- }
- return rangePoints;
- }
- // a nearest neighbor in the set to point p; null if the set is empty
- public Point2D nearest(Point2D p) {
- if (null == p) throw new IllegalArgumentException();
- if (pointsBST.isEmpty()) {
- return null;
- } else {
- // any point in the SET will be a starting point champion
- Point2D championPoint = pointsBST.iterator().next();
- for (Point2D point2D : pointsBST) {
- if (point2D.distanceSquaredTo(p) < championPoint.distanceSquaredTo(p)) {
- // we have a new champion
- championPoint = point2D;
- }
- }
- return championPoint;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement