Skip to content

Full Example Program

Eric Regina edited this page Mar 20, 2016 · 4 revisions

Below is a simple command line program example showing how to use the KDTree.

class Program
{
	public static double[][] GenerateData(int points, double range)
	{
		var data = new List<double[]>();
		var random = new Random();

		for (int i = 0; i < points; i++)
		{
			data.Add(new double[] { (random.NextDouble() * range), (random.NextDouble() * range) });
		}

		return data.ToArray();
	}

	static void Main(string[] args)
	{
		// Define the metric function
		Func<double[], double[], double> L2Norm = (x, y) =>
			{
				double dist = 0f;
				for (int i = 0; i < x.Length; i++)
				{
					dist += (x[i] - y[i]) * (x[i] - y[i]);
				}

				return dist;
			};

		// Generate some data for the tree and testing
		var treeData = GenerateData(1000000, 1000);
		var testData = GenerateData(10000, 1000);
		var tree = new KDTree<double>(2, treeData, L2Norm);

		// Measure the time to search
		var stopwatch = new Stopwatch();
		stopwatch.Start();
		for (int i = 0; i < testData.Length; i++)
		{
			// Get the three closest points from the target
			var test = tree.NearestNeighbors(testData[i], 3);

			// Get all points with in a distance of 100 from the target.
			var test2 = tree.RadialSearch(center: testData[i], radius: 100);
		}
		stopwatch.Stop();

		Console.WriteLine("Milliseconds: " + stopwatch.ElapsedMilliseconds);
		Console.Read();
	}
}

Clone this wiki locally