How can I generate a random 64 bit unsigned integer in Go?
First I need to call
rand.Seed(0)
and then I need a function that returns a uint64 with the following signature
func random(min, max uint64) uint64 {
}
The function above should return a random 64 bit unsigned integer in the range [min, max] (min and max included)
I'm not sure why you are being downvoted. I think you are worried about the case where max - min
is greater than MaxInt64 in which case rand.Int63n
would fail as you have remarked. I would handle that case separately.
const maxInt64 uint64 = 1 << 63 - 1
func random(min, max uint64) uint64 {
return randomHelper(max - min) + min
}
func randomHelper(n uint64) uint64 {
if n < maxInt64 {
return uint64(rand.Int63n(int64(n+1)))
}
x := rand.Uint64()
for x > n {
x = rand.Uint64()
}
return x
}