Kd::Tree
Crystal implementation of "K-Dimensional Tree" and "N-Nearest Neighbors" based on http://en.wikipedia.org/wiki/Kd-tree.
Installation
Add this to your application's shard.yml
:
dependencies:
kdtree:
github: mamantoha/kd_tree
Usage
require "kd_tree"
Construct a new tree. Each point should be of the form [x, y]
, where x
and y
are floats:
kd = Kd::Tree.new(points)
Find the nearest point to [x, y]
. Returns an array with one point:
kd.nearest([x, y])
Find the nearest k
points to [x, y]
. Returns an array of points:
kd.nearest([x, y], k)
Example
require "kd_tree"
points = [
[2.0, 3.0],
[5.0, 4.0],
[4.0, 7.0],
[7.0, 2.0],
[8.0, 1.0],
[9.0, 6.0],
]
kd = Kd::Tree.new(points)
kd.nearest([1.0, 1.0])
# => [[2.0, 3.0]])
kd_tree.nearest([1.0, 1.0], 2)
# => [[2.0, 3.0], [5.0, 4.0]])
Contributing
- Fork it (https://github.com/mamantoha/kd_tree/fork)
- Create your feature branch (
git checkout -b my-new-feature
) - Commit your changes (
git commit -am 'Add some feature'
) - Push to the branch (
git push origin my-new-feature
) - Create a new Pull Request
Contributors
- mamantoha Anton Maminov - creator, maintainer