File: kd_tree.rb [algorithms-0.6.1 Documentation]

Last Modified
  2015-05-10 11:38:21 +0000
Requires

## Description

A kd-tree is a binary tree that allows one to store points (of any space dimension: 2D, 3D, etc). The structure of the resulting tree makes it so that large portions of the tree are pruned during queries.

One very good use of the tree is to allow nearest neighbor searching. Let's say you have a number of points in 2D space, and you want to find the nearest 2 points from a specific point:

First, put the points into the tree:

    kdtree = Containers::KDTree.new( {0 => [4, 3], 1 => [3, 4], 2 => [-1, 2], 3 => [6, 4],
                                     4 => [3, -5], 5 => [-2, -5] })

Then, query on the tree:

    puts kd.find_nearest([0, 0], 2) => [[5, 2], [9, 1]]

The result is an array of [distance, id] pairs. There seems to be a bug in this version.

Note that the point queried on does not have to exist in the tree. However, if it does exist, it will be returned.