美文网首页Go golangGo
golang抽奖随机代码

golang抽奖随机代码

作者: wuhan_goer | 来源:发表于2022-02-09 23:48 被阅读0次
 package main

import (
   "fmt"
   "math/rand"
   "time"
)
// 奖品
type PrizeInfo struct {
   PrizeId int // 奖品id
   Weight  int // 概率 
}

func main() {
   var list []PrizeInfo
   list = []PrizeInfo{
       {
           PrizeId: 1,
           Weight:  10,
       },
       {
           PrizeId: 2,
           Weight:  20,
       },
       {
           PrizeId: 3,
           Weight:  50,
       },
       {
           PrizeId: 4,
           Weight:  20,
       },
   }
   m := make(map[int]int)
   for i := 0; i < 1000; i++ {
       prize := GetRandom(list)
       m[prize.PrizeId] += 1
   }
   fmt.Println(m)

}
// 随机并返回抽中的奖品
func GetRandom(list []PrizeInfo) PrizeInfo {
   if len(list) == 0 {
       return PrizeInfo{}
   }
   total := 0
   for _, v := range list {
       total += v.Weight
   }
   rand.Seed(time.Now().UnixNano())
   index := rand.Intn(total) // [0,99 )
   current := 0
   for _, v := range list {
       current += v.Weight
       if index < current {
           return v
       }

   }
   return PrizeInfo{}

}

output:
map[1:89 2:189 3:511 4:211]

相关文章

网友评论

    本文标题:golang抽奖随机代码

    本文链接:https://www.haomeiwen.com/subject/cvogkrtx.html