-2

I need to generate an unique random number in Golang. I have a simple ruby code for it:

(0...16).map { rand(10).to_s }.join

So, effectively i need to generate a number of length 16 where each digit is randomly picked up from [0-9]. I did not understand how random.Intn(n) function can help me. Any idea how can I do this?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Agniswar Bakshi
  • 328
  • 5
  • 21
  • 3
    Exactly the same way? Generate 16 digits and join them. Hint (if you actually need a number not a string): `v = v * 10 + randomDigit` – zerkms Jan 10 '18 at 07:36
  • 1
    It's probably more efficient (in both Go and Ruby) to just generate a single random number between 0 and 1*10ˆ16-1. – Jonathan Hall Jan 10 '18 at 08:35
  • 1
    Also for a fast general solution (when you need not just digits and / or you need longer than what fits into an `int64`), see [How to generate a random string of a fixed length in golang?](https://stackoverflow.com/questions/22892120/how-to-generate-a-random-string-of-a-fixed-length-in-golang/31832326#31832326) – icza Jan 10 '18 at 08:45

1 Answers1

4

One way is:

s := ""
for i := 0; i < 16; i++ {
    s += (string)(rand.Intn(10) + 48)
}

48 is the ascii value for 0.

Or by using @Flimzy's more efficient suggestion:

s := fmt.Sprintf("%016d", rand.Int63n(1e16))

where "%016d" will help pad the number with zeros.

ANisus
  • 74,460
  • 29
  • 162
  • 158
  • Wouldn't you want to seed that random in some form? – Andrew Jan 10 '18 at 12:21
  • @Andrew Yes, you surely need to [seed](https://golang.org/pkg/math/rand/#Seed). Check https://stackoverflow.com/questions/12321133/golang-random-number-generator-how-to-seed-properly for that. – ANisus Jan 11 '18 at 07:56