-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweightrand.go
83 lines (65 loc) · 1.13 KB
/
weightrand.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
package rand
import (
"sync"
)
type SeedType interface {
any
}
type Item[T SeedType] struct {
item T
weight int
}
type WeightRand[T SeedType] struct {
seed []*Item[T]
weight int
lock *sync.Mutex
}
func NewWeightRand[T SeedType](items ...T) *WeightRand[T] {
w := &WeightRand[T]{
lock: &sync.Mutex{},
}
for _, it := range items {
w.Add(it)
}
return w
}
func (w *WeightRand[T]) Add(it T) {
w.AddWeight(it, 1)
}
func (w *WeightRand[T]) AddWeight(it T, weight int) {
defer w.calc()
w.seed = append(w.seed, &Item[T]{
item: it,
weight: weight,
})
}
func (w *WeightRand[T]) calc() {
w.lock.Lock()
defer w.lock.Unlock()
w.weight = 0
for _, it := range w.seed {
w.weight += it.weight
}
}
func (w *WeightRand[T]) Update(fn func(T, int) (T, int)) {
w.lock.Lock()
defer w.lock.Unlock()
for _, it := range w.seed {
it.item, it.weight = fn(it.item, it.weight)
}
}
func (w *WeightRand[T]) Get() (t T) {
w.lock.Lock()
defer w.lock.Unlock()
stop := Intn(w.weight)
sum := 0
for _, it := range w.seed {
if it.weight == 0 {
continue
}
if sum += it.weight; sum > stop {
return it.item
}
}
return
}