2 Star 1 Fork 0

张明理/sfw

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
weights.go 925 Bytes
一键复制 编辑 原始数据 按行查看 历史
张明理 提交于 2020-09-30 12:43 . Initial commit of sfw
package urand
import "math/rand"
// Weights 权重列表
type Weights interface {
TotalLen() int
TotalWeight() int
GetWeight(int) int
}
// RandInWeights 计算权重,并返回数组下标
func RandInWeights(weightList Weights) int {
chance := rand.Intn(weightList.TotalWeight())
var up int
for i := 0; i < weightList.TotalLen(); i++ {
up += weightList.GetWeight(i)
if chance < up {
return i
}
}
return weightList.TotalLen() - 1
}
// BaseWeights 将 []int 包装为 Weights 接口
type BaseWeights []int
// TotalLen 总长度
func (b BaseWeights) TotalLen() int { return len(b) }
// TotalWeight 总权重
func (b BaseWeights) TotalWeight() int {
total := 0
for _, w := range b {
total += w
}
return total
}
// GetWeight 获取指定权重
func (b BaseWeights) GetWeight(i int) int { return b[i] }
// Wrap 将 []int 包装为baseWeights
func Wrap(v []int) BaseWeights { return BaseWeights(v) }
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/terender/sfw.git
git@gitee.com:terender/sfw.git
terender
sfw
sfw
v0.2.8

搜索帮助