예제 #1
0
파일: KDTree.cs 프로젝트: htna/explsolv
        /**
         * Find KD-tree nodes whose keys are <I>n</I> nearest neighbors to
         * key. Uses algorithm above.  Neighbors are returned in ascending
         * order of distance to key.
         *
         * @param key key for KD-tree node
         * @param n how many neighbors to find
         *
         * @return objects at node nearest to key, or null on failure
         *
         * @throws KeySizeException if key.length mismatches K
         * @throws IllegalArgumentException if <I>n</I> is negative or
         * exceeds tree size
         */
        public TYPE[] nearest(double[] key, int n)
        {
            if (n < 0 || n > m_count)
            {
                throw new ArgumentException("Number of neighbors cannot be negative or greater than number of nodes");
            }

            if (key.Length != m_K)
            {
                throw new KeySizeException();
            }

            TYPE[] nbrs             = new TYPE[n];
            NearestNeighborList nnl = new NearestNeighborList(n);

            // initial call is with infinite hyper-rectangle and max distance
            HRect  hr           = HRect.infiniteHRect(key.Length);
            double max_dist_sqd = Double.MaxValue;
            HPoint keyp         = new HPoint(key);

            KDNode.nnbr(m_root, keyp, hr, max_dist_sqd, 0, m_K, nnl);

            for (int i = 0; i < n; ++i)
            {
                KDNode kd = (KDNode)nnl.removeHighest();
                nbrs[n - i - 1] = kd.v;
            }

            return(nbrs);
        }