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 c51单片机控制步进电机
  • ¥20 Visual studio无法检测到设备
  • ¥15 为什么我通过html绘制的SVG折线图插入到word中坐标轴不显示出来
  • ¥30 vue 页面窗口放大或者缩小元素会变化
  • ¥15 questasim仿真报错
  • ¥15 寻找电脑攻防的导师,有问题请教一下。
  • ¥20 微信同是win11,我的电脑安装不了pageoffice,一直无法打开
  • ¥15 这个界面我通过postman请求不到,但是通过浏览器可以正常访问
  • ¥15 多目标优化算法在与其他算法数据对比结果判断
  • ¥15 CPTN和EAST,主干网络是VGG16,请问在ICDAR2015数据集上训练之后,CPTN和EAST模型的大小为多少