I'm translating a tool from C++ to Go. The C++ tool uses the boost::random library and invokes boost::uniform_int. I'd like to know if there's a comparable 'out of the box' function in Go. If not I need some help building my own.
I've combed through Go's math/rand package but didn't find anything that was obviously equivalent.
Here's a link to boost's documentation
This is function declaration/invocation in the C++ tool
boost::uniform_int<unsigned int> randomDistOp(1, 100);
The Intn
method should give you what you want.
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
fmt.Println(1 + r.Intn(100))
}
This provides uniformly random integers from [0, n). To set a different lower bound, just add it to the result. Just to be clear, Intn(100)
will return numbers up to but excluding 100, so adding 1 will give you the proper range from 1 to 100.