diff --git a/comm/core.go b/comm/core.go index c5fe6c7f1..53f909092 100644 --- a/comm/core.go +++ b/comm/core.go @@ -2,10 +2,10 @@ package comm import ( "context" - "math/rand" - + "crypto/rand" "fmt" "go_dreamfactory/pb" + "math/big" "reflect" "strings" @@ -93,15 +93,16 @@ func ProtoMarshal(rsp proto.Message, msg *pb.UserMessage) (ok bool) { /// 参数 权重数组 返回值 数组下标 func GetRandW(sz []int32) int32 { if len(sz) > 0 { - var _totalW int32 // 总权重 - var _tmpW int32 // 临时权重 + var _totalW int64 // 总权重 + var _tmpW int64 // 临时权重 for _, v := range sz { - _totalW += v + _totalW += int64(v) } // 随机权重 + n, _ := rand.Int(rand.Reader, big.NewInt(_totalW)) for i, v := range sz { - _tmpW += v - if rand.Int31n(_totalW) < _tmpW { + _tmpW += int64(v) + if n.Int64() < _tmpW { return int32(i) } } @@ -117,7 +118,8 @@ func GetRandNum(min, max int32) int32 { return min } - return rand.Int31n(int32(max-min+1)) + min + n, _ := rand.Int(rand.Reader, big.NewInt(int64(max-min+1))) //+1 是因为 rand方法范围是[0, max) + return int32(n.Int64()) + min } ///通过uid获取用户所在区服