forked from cchamplin/gocrush
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crush.go
110 lines (105 loc) · 2.07 KB
/
crush.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package gocrush
func Select(parent Node, input int64, count int, nodeType int, c Comparator) []Node {
var results []Node
//if len(parent.Children) < count {
// panic("Asked for more node than are available")
//}
var rPrime = int64(0)
for r := 1; r <= count; r++ {
var failure = 0
var loopbacks = 0
var escape = false
var retryOrigin = false
var out Node
for {
retryOrigin = false
var in = parent
var skip = make(map[Node]bool)
var retryNode = false
for {
retryNode = false
rPrime = int64(r + failure)
out = in.Select(input, rPrime)
if out.GetType() != nodeType {
in = out
retryNode = true
} else {
if contains(results, out) {
if !nodesAvailable(in, results, skip) {
if loopbacks == 150 {
escape = true
break
}
loopbacks += 1
retryOrigin = true
} else {
retryNode = true
}
failure += 1
} else if c != nil && !c(out) {
skip[out] = true
if !nodesAvailable(in, results, skip) {
if loopbacks == 150 {
escape = true
break
}
loopbacks += 1
retryOrigin = true
} else {
retryNode = true
}
failure += 1
} else if isDefunct(out) {
failure++
if loopbacks == 150 {
escape = true
break
}
loopbacks += 1
retryOrigin = true
} else {
break
}
}
if !retryNode {
break
}
}
if !retryOrigin {
break
}
}
if escape {
continue
}
results = append(results, out)
}
return results
}
func nodesAvailable(parent Node, selected []Node, rejected map[Node]bool) bool {
var children = parent.GetChildren()
for _, child := range children {
if !isDefunct(child) {
if ok := contains(selected, child); !ok {
if _, ok := rejected[child]; !ok {
return true
}
}
}
}
return false
}
func contains(s []Node, n Node) bool {
for _, a := range s {
if a == n {
return true
}
}
return false
}
func isDefunct(n Node) bool {
if n.IsLeaf() && n.IsFailed() {
return true
}
return false
}