Skip to content

Instantly share code, notes, and snippets.

@lgrains
Created May 12, 2014 13:41
Show Gist options
  • Save lgrains/116dad5aa2cb4daeccdb to your computer and use it in GitHub Desktop.
Save lgrains/116dad5aa2cb4daeccdb to your computer and use it in GitHub Desktop.
IRB session using the kdtree gem
>> require 'kdtree'
true
>> point_array = [ [3,5],[14,0],[0,3],[-5,6],[-2,-3],[-4,-7],[2,-5],[0,0] ]
[
[0] [
[0] 3,
[1] 5
],
[1] [
[0] 14,
[1] 0
],
[2] [
[0] 0,
[1] 3
],
[3] [
[0] -5,
[1] 6
],
[4] [
[0] -2,
[1] -3
],
[5] [
[0] -4,
[1] -7
],
[6] [
[0] 2,
[1] -5
],
[7] [
[0] 0,
[1] 0
]
]
>> point_array.each_with_index{|e,i| e << i}
[
[0] [
[0] 3,
[1] 5,
[2] 0
],
[1] [
[0] 14,
[1] 0,
[2] 1
],
[2] [
[0] 0,
[1] 3,
[2] 2
],
[3] [
[0] -5,
[1] 6,
[2] 3
],
[4] [
[0] -2,
[1] -3,
[2] 4
],
[5] [
[0] -4,
[1] -7,
[2] 5
],
[6] [
[0] 2,
[1] -5,
[2] 6
],
[7] [
[0] 0,
[1] 0,
[2] 7
]
]
>> point_array.inject(points){ |array, element| array << element; array}
[
[0] [
[0] 3,
[1] 5,
[2] 0
],
[1] [
[0] 14,
[1] 0,
[2] 1
],
[2] [
[0] 0,
[1] 3,
[2] 2
],
[3] [
[0] -5,
[1] 6,
[2] 3
],
[4] [
[0] -2,
[1] -3,
[2] 4
],
[5] [
[0] -4,
[1] -7,
[2] 5
],
[6] [
[0] 2,
[1] -5,
[2] 6
],
[7] [
[0] 0,
[1] 0,
[2] 7
]
]
>> kd = Kdtree.new(point_array)
#<Kdtree:0x007ff443d21e48>
>> p kd.nearest(-2,-3)
4
4
>> p kd.nearestk(-2,-3,5)
[4, 7, 6, 5, 2]
[
[0] 4,
[1] 7,
[2] 6,
[3] 5,
[4] 2
]
>> kd.nearestk(-2,-3,5).each{|index| p point_array[index] }
[-2, -3, 4]
[0, 0, 7]
[2, -5, 6]
[-4, -7, 5]
[0, 3, 2]
[
[0] 4,
[1] 7,
[2] 6,
[3] 5,
[4] 2
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment