-
Notifications
You must be signed in to change notification settings - Fork 43
/
random_weighted.go
75 lines (64 loc) · 1.65 KB
/
random_weighted.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 weighted
import (
"time"
"golang.org/x/exp/rand"
)
// randWeighted is a wrapped weighted item that is used to implement weighted random algorithm.
type randWeighted struct {
Item interface{}
Weight int
}
// RandW is a struct that contains weighted items implement weighted random algorithm.
type RandW struct {
items []*randWeighted
n int
sumOfWeights int
r *rand.Rand
}
// NewRandW creates a new RandW with a random object.
func NewRandW() *RandW {
return &RandW{r: rand.New(rand.NewSource(uint64(time.Now().UnixNano())))}
}
// Next returns next selected item.
func (rw *RandW) Next() (item interface{}) {
if rw.n == 0 {
return nil
}
if rw.sumOfWeights <= 0 {
return nil
}
randomWeight := rw.r.Intn(rw.sumOfWeights) + 1
for _, item := range rw.items {
randomWeight = randomWeight - item.Weight
if randomWeight <= 0 {
return item.Item
}
}
return rw.items[len(rw.items)-1].Item
}
// Add adds a weighted item for selection.
func (rw *RandW) Add(item interface{}, weight int) {
rItem := &randWeighted{Item: item, Weight: weight}
rw.items = append(rw.items, rItem)
rw.sumOfWeights += weight
rw.n++
}
// All returns all items.
func (rw *RandW) All() map[interface{}]int {
m := make(map[interface{}]int)
for _, i := range rw.items {
m[i.Item] = i.Weight
}
return m
}
// RemoveAll removes all weighted items.
func (rw *RandW) RemoveAll() {
rw.items = make([]*randWeighted, 0)
rw.n = 0
rw.sumOfWeights = 0
rw.r = rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
}
// Reset resets the balancing algorithm.
func (rw *RandW) Reset() {
rw.r = rand.New(rand.NewSource(uint64(time.Now().UnixNano())))
}