From 0e2481dde36a5f188390a0a7ef24b785b5ba4faa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9my=20Zurcher?= Date: Tue, 26 Mar 2013 17:55:52 +0100 Subject: Algorithms-I : 5-kdtrees: implement PointSET --- Algorithms/Part-I/5-KdTrees/PointSET.java | 34 ++++++++++++++++++++++++++----- 1 file changed, 29 insertions(+), 5 deletions(-) diff --git a/Algorithms/Part-I/5-KdTrees/PointSET.java b/Algorithms/Part-I/5-KdTrees/PointSET.java index aabceff..f5594de 100644 --- a/Algorithms/Part-I/5-KdTrees/PointSET.java +++ b/Algorithms/Part-I/5-KdTrees/PointSET.java @@ -1,50 +1,74 @@ /* vim: set expandtab tabstop=4 shiftwidth=4 : */ +import java.util.TreeSet; + public class PointSET { + private TreeSet set; // construct an empty set of points public PointSET() { + set = new TreeSet(); } // is the set empty? public boolean isEmpty() { - return true; + return set.isEmpty(); } // number of points in the set public int size() { - return 0; + return set.size(); } // add the point p to the set (if it is not already in the set) public void insert(Point2D p) { + set.add(p); } // does the set contain the point p? public boolean contains(Point2D p) { - return false; + return set.contains(p); } // draw all of the points to standard draw public void draw() { + for (Point2D p : set) p.draw(); } // all points in the set that are inside the rectangle public Iterable range(RectHV rect) { - return null; + Stack stack = new Stack(); + + for (Point2D p : set) + if (rect.contains(p)) stack.push(p); + + return stack; } // a nearest neighbor in the set to p; null if set is empty public Point2D nearest(Point2D p) { - return null; + if (set.isEmpty()) return null; + + Point2D p0 = null; + double d = Double.MAX_VALUE; + for (Point2D o : set) + { + double d2 = p.distanceTo(o); + if (d2 < d) { + d = d2; + p0 = o; + } + } + return p0; + } } -- cgit v1.1-2-g2b99