37 lines
647 B
Go
37 lines
647 B
Go
package comm
|
|
|
|
import "math/rand"
|
|
|
|
type WeightItem struct {
|
|
Id interface{}
|
|
Weight int
|
|
}
|
|
|
|
// 权重项目
|
|
type WeightedRandom struct {
|
|
items []*WeightItem
|
|
totalWeight int
|
|
}
|
|
|
|
func NewWeightedRandom(items []*WeightItem) *WeightedRandom {
|
|
wr := &WeightedRandom{items: items}
|
|
for _, item := range wr.items {
|
|
wr.totalWeight += int(item.Weight)
|
|
}
|
|
return wr
|
|
}
|
|
|
|
func (wr *WeightedRandom) Pick() *WeightItem {
|
|
if wr.totalWeight <= 0 {
|
|
return nil
|
|
}
|
|
randomNumber := rand.Intn(wr.totalWeight)
|
|
for _, item := range wr.items {
|
|
if randomNumber < int(item.Weight) {
|
|
return item
|
|
}
|
|
randomNumber -= int(item.Weight)
|
|
}
|
|
return nil
|
|
}
|