using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KDTree { /// /// An interface which enables flexible distance functions. /// public interface DistanceFunctions { /// /// Compute a distance between two n-dimensional points. /// /// The first point. /// The second point. /// The n-dimensional distance. double Distance(double[] p1, double[] p2); /// /// Find the shortest distance from a point to an axis aligned rectangle in n-dimensional space. /// /// The point of interest. /// The minimum coordinate of the rectangle. /// The maximum coorindate of the rectangle. /// The shortest n-dimensional distance between the point and rectangle. double DistanceToRectangle(double[] point, double[] min, double[] max); } /// /// A distance function for our KD-Tree which returns squared euclidean distances. /// public class SquareEuclideanDistanceFunction : DistanceFunctions { /// /// Find the squared distance between two n-dimensional points. /// /// The first point. /// The second point. /// The n-dimensional squared distance. public double Distance(double[] p1, double[] p2) { double fSum = 0; for (int i = 0; i < p1.Length; i++) { double fDifference = (p1[i] - p2[i]); fSum += fDifference * fDifference; } return fSum; } /// /// Find the shortest distance from a point to an axis aligned rectangle in n-dimensional space. /// /// The point of interest. /// The minimum coordinate of the rectangle. /// The maximum coorindate of the rectangle. /// The shortest squared n-dimensional squared distance between the point and rectangle. public double DistanceToRectangle(double[] point, double[] min, double[] max) { double fSum = 0; double fDifference = 0; for (int i = 0; i < point.Length; ++i) { fDifference = 0; if (point[i] > max[i]) fDifference = (point[i] - max[i]); else if (point[i] < min[i]) fDifference = (point[i] - min[i]); fSum += fDifference * fDifference; } return fSum; } } }