有比得上boost::uniform_int的Go函数吗?
Is there Go function comparable to boost::uniform_int?
我正在将一个工具从 C++ 翻译成 Go。 C++ 工具使用 boost::random 库并调用 boost::uniform_int。我想知道 Go 中是否有类似的 'out of the box' 函数。如果没有,我需要一些帮助来构建我自己的。
我梳理了 Go 的 math/rand 包,但没有找到任何明显等效的东西。
这里是 a link 以提升文档
这是 C++ 工具中的函数 declaration/invocation
boost::uniform_int<unsigned int> randomDistOp(1, 100);
Intn
方法应该可以满足您的需求。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
fmt.Println(1 + r.Intn(100))
}
这提供了 [0, n) 中的均匀随机整数。要设置不同的下限,只需将其添加到结果中即可。需要明确的是,Intn(100)
将 return 数字最大但不包括 100,因此加 1 将为您提供从 1 到 100 的正确范围。
我正在将一个工具从 C++ 翻译成 Go。 C++ 工具使用 boost::random 库并调用 boost::uniform_int。我想知道 Go 中是否有类似的 'out of the box' 函数。如果没有,我需要一些帮助来构建我自己的。
我梳理了 Go 的 math/rand 包,但没有找到任何明显等效的东西。
这里是 a link 以提升文档
这是 C++ 工具中的函数 declaration/invocation
boost::uniform_int<unsigned int> randomDistOp(1, 100);
Intn
方法应该可以满足您的需求。
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
r := rand.New(rand.NewSource(time.Now().UnixNano()))
fmt.Println(1 + r.Intn(100))
}
这提供了 [0, n) 中的均匀随机整数。要设置不同的下限,只需将其添加到结果中即可。需要明确的是,Intn(100)
将 return 数字最大但不包括 100,因此加 1 将为您提供从 1 到 100 的正确范围。