加权随机算法改良版
func (this *LoadBalance) SelectByWeightBetter(ip string) *HttpServer { rand.Seed(time.Now().UnixNano()) sumList := make([]int, len(this.Servers)) //this.servers是服务器列表 sum := 0 for i := 0; i < len(this.Servers); i++ { sum += this.Servers[i].Weight //如果是5,7,9权重之和为5 12 21,分三个区间[0:5) [5:12) [12,21) 0-20的随机数落在哪个区间就代表当前随机是哪个权重 sumList[i] = sum //生成权重区间列表 } _rand := rand.Intn(sum) for index, value := range sumList { if _rand < value { //因为sumList是递增的,而且长度等于this.Servers所以遍历它比较随机数落在哪个区间就可以得到当前的权重是哪个 return this.Servers[index] } } return this.Servers[0] }
加权随机算法单独实现
package main import "fmt" import "time" import "math/rand" func main() { a := make([]int,0) a = append(a,2,3,5) sum := 0 b := make([]int,len(a)) for i,v := range a{ sum += v b[i] = sum } rand.Seed(time.Now().UnixNano()) _rand := rand.Intn(sum) fmt.Println(_rand) for index, value := range b { if _rand < value { fmt.Println(a[index]) break } }
相关推荐
Happyunlimited 2020-04-30
troysps 2020-03-04
风吹夏天 2020-01-24
yedaoxiaodi 2020-01-06
魏莉的微 2019-12-19
shawsun 2019-12-15
baike 2019-12-08
微分 2018-03-02
Qunicy 2019-07-09
郭岚 2019-06-28
YUAN 2019-06-28
ZhuZhuWonder 2019-06-17
MachineIntellect 2015-07-10
蜗牛慢爬的李成广 2019-05-12
StrongHYQ 2018-07-01