'How to generate a fixed length random number in Go?

What is the fastest and simplest way to generate fixed length random numbers in Go?

Say to generate 8-digits long numbers, the problem with rand.Intn(100000000) is that the result might be far less than 8-digits, and padding it with leading zeros doesn't look like a good answer to me.

I.e., I care about the the quality of the randomness more in the sense of its length. So I'm thinking, for this specific problem, would the following be the fastest and simplest way to do it?

99999999 - rand.Int63n(90000000)

I.e., I guess Int63n might be better for my case than Intn. Is it ture, or it is only a wishful thinking? Regarding randomness of the full 8-digits, would the two be the same, or there is really one better than the other?

Finally, any better way than above?

UPDATE:

Please do not provide low + rand(hi-low) as the answer, as everyone knows that. It is equivalent of what I'm doing now, and it doesn't answer my real question, "Regarding randomness of the full 8-digits, would the two be the same, or there is really one better than the other? "

If nobody can answer that, I'll plot a 2-D scatter plot between the two and find out myself...

Thanks



Solution 1:[1]

It depend on value range you want to use.

  1. If you allow value range [0-99999999] and padding zero ip number of char < 8, then use fmt like fmt.Sprintf("%08d",rand.Intn(100000000)).

  2. If you dont want padding, which value in range [10000000, 99999999], then give it a base like ranNumber := 10000000 + rand.Intn(90000000)`

Solution 2:[2]

See it on Playground

crypto/rand package is used to generate number.

func generateRandomNumber(numberOfDigits int) (int, error) {
    maxLimit := int64(int(math.Pow10(numberOfDigits)) - 1)
    lowLimit := int(math.Pow10(numberOfDigits - 1))

    randomNumber, err := rand.Int(rand.Reader, big.NewInt(maxLimit))
    if err != nil {
        return 0, err
    }
    randomNumberInt := int(randomNumber.Int64())

    // Handling integers between 0, 10^(n-1) .. for n=4, handling cases between (0, 999)
    if randomNumberInt <= lowLimit {
        randomNumberInt += lowLimit
    }

    // Never likely to occur, kust for safe side.
    if randomNumberInt > int(maxLimit) {
        randomNumberInt = int(maxLimit)
    }
    return randomNumberInt, nil
}

Solution 3:[3]

@Aditya, I think soup.find("span") will only return the first "span" and you want the text from the second one. I would try:

for item in soup.select("div._9uwBC.wY0my"):
    spans = item.find_all("span")
    for span in spans:
        n = span.text
        if n != '':
            print(n)

Which should print the text of the non-empty span tags, under the you specified. Does accomplish what you want?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 secmask
Solution 2 Rajat Goyal
Solution 3