加权随机算法改良版

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
        }
    }




原文地址:https://www.cnblogs.com/hualou/p/12070686.html