duanlei4759 2017-06-27 07:27
浏览 70
已采纳

如何在Go中生成可变长度的随机数

I'm trying to generate a random integer with variable length in Go but I always get the number filling the total length. Here's my code:

package main

import (
    "fmt"
    "math/big"
    "crypto/rand"
)

const ResultsPerPage = 30

var (
        total = new(big.Int).SetBytes([]byte{
                0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
                0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x40,
        })
        pages = new(big.Int).Div(total, big.NewInt(ResultsPerPage))
        random *big.Int
        err error
)

func main() {

fmt.Println(pages)
fmt.Println(randomString(pages))
}

func randomString(l *big.Int) string {
  random, err = rand.Int(rand.Reader, l)
  fmtrandom := fmt.Sprint(random)
  return string(fmtrandom)
}

Outputs

3859736307910539847452366166956263595094585475969163479420172104717272049811
3479662380009045046388212253547512051795238437604387552617121977169155584415

Code sample: https://play.golang.org/p/HxAb6Rs_Uj

Any help is appreciated. Thank you.

  • 写回答

1条回答 默认 最新

  • dtmm0148603 2017-06-27 07:36
    关注

    If I understand correctly, the issue you're having is that the random number appears to always have the same number of digits as the maximum allowed value, right? When I run the code, this is not the case. Here's an output I just observed:

    3859736307910539847452366166956263595094585475969163479420172104717272049811
    65719900872761032562423535702578352960653752260368991759410130265294153783
    

    In the playground, I believe the random seed and clock time are fixed, so you'll see the same result repeatedly. But running locally, I see the expected variation in the length of the output.

    UPDATE

    You may wonder why you can run this code a bunch of times and observe that the length of the random number is very often close to the length of the maximum value.

    A little math explains this. Let's imagine we're picking a number between 0 and 999. How many numbers in that range have:

    1. 3 digits? 900 (100-999)
    2. 2 digits? 90 (10-99)
    3. 1 digit? 10 (0-9)

    Similarly, with your very large maximum value, most of the numbers that can be picked will be very close to that maximum length. It will be rare to see a number two digits short of that length. (You should see them on the order of 1% of the time.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题