想用go实现一个按着设置的概率产生一定范围内的随机数,请大牛指教

karl_zhao · · 4687 次点击
```go package main import ( "fmt" "math/rand" "time" ) type randItem struct { start float64 end float64 } func GetRandItem(items map[interface{}]float64) interface{} { nums := make(map[interface{}]randItem) var s float64 for k, f := range items { if f <= 0 { continue } nums[k] = randItem{ start: s, end: s + f, } s = nums[k].end } rnd := rand.Float64() * s for k, f := range nums { if f.start <= rnd && f.end > rnd { return k } } return nil } func main() { rand.Seed(time.Now().UnixNano()) type info struct { Start int End int } mItems := map[interface{}]float64{ info{ Start: 0, End: 15, }: 0.5, info{ Start: 16, End: 31, }: 0.2, info{ Start: 32, End: 64, }: 0.2, info{ Start: 65, End: 128, }: 0.1, } item := GetRandItem(mItems).(info) fmt.Println("===", item) } ```
#8
更多评论
import ( "crypto/rand" "fmt" "math/big" ) func nrand(l int64) uint32 { max := big.NewInt(l) bigx, _ := rand.Int(rand.Reader, max) x := bigx.Int64() return uint32(x) } func genNumber() uint32{ g := nrand(100) if g < 50 { return nrand(16) } if g < 70 { return 16 + nrand(16) } if g < 90 { return 32 + nrand(32) } return 64 + nrand(64) } func main(){ var p0, p1 ,p2 ,p3 []uint32 for i:= 0 ; i< 1000 ; i++ { g := genNumber() if g < 16 { p0 = append(p0, g) continue } if g < 32 { p1 = append(p1,g) continue } if g < 64 { p2 = append(p2,g) continue } p3 = append(p3,g) } fmt.Printf("0~15 %v\n", len(p0)) fmt.Printf("16~32 %v\n", len(p1)) fmt.Printf("32~64 %v\n", len(p2)) fmt.Printf("64~128 %v\n", len(p3)) }
#1
buscoop
纸上得来终觉浅,绝知此事要躬行!
很好看!!
#2