forked from agatan/bktree
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbktree.go
75 lines (67 loc) · 1.25 KB
/
bktree.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package bktree
type BKTree struct {
root *node
}
type node struct {
entry Entry
children []struct {
distance int
node *node
}
}
func (n *node) addChild(e Entry) {
newnode := &node{entry: e}
loop:
d := n.entry.Distance(e)
for _, c := range n.children {
if c.distance == d {
n = c.node
goto loop
}
}
n.children = append(n.children, struct {
distance int
node *node
}{d, newnode})
}
type Entry interface {
Distance(Entry) int
}
func (bk *BKTree) Add(entry Entry) {
if bk.root == nil {
bk.root = &node{
entry: entry,
}
return
}
bk.root.addChild(entry)
}
type Result struct {
Distance int
Entry Entry
}
func (bk *BKTree) Search(needle Entry, tolerance int) []*Result {
results := make([]*Result, 0)
if bk.root == nil {
return results
}
candidates := []*node{bk.root}
for len(candidates) != 0 {
c := candidates[len(candidates)-1]
candidates = candidates[:len(candidates)-1]
d := c.entry.Distance(needle)
if d <= tolerance {
results = append(results, &Result{
Distance: d,
Entry: c.entry,
})
}
low, high := d-tolerance, d+tolerance
for _, c := range c.children {
if low <= c.distance && c.distance <= high {
candidates = append(candidates, c.node)
}
}
}
return results
}