问题描述
我想拥有一个可以调用的函数,以便在每次调用时获得随机的true
或false
:
I want to have a function that I can call to get a random true
or false
on each call:
randBoolean() // true
randBoolean() // false
randBoolean() // false
randBoolean() // true
如何返回随机布尔值?
推荐答案
您需要某种随机信息,根据它的值,您可以在一半的可能情况下返回true
,在返回的情况下返回false
.其他一半的情况.
You need some kind of random information, and based on its value, you can return true
in half of its possible cases, and false
in the other half of the cases.
使用 math/rand
包:
func rand1() bool {
return rand.Float32() < 0.5
}
不要忘记为math/rand
程序包正确植入种子,以使其在使用 rand.Seed()
:
Don't forget to properly seed the math/rand
package for it to be different on each app run using rand.Seed()
:
func main() {
rand.Seed(time.Now().UnixNano())
fmt.Println(rand1())
}
math/rand
的打包文档中提到了这一点:
This is mentioned in the package doc of math/rand
:
如果不设置种子,则每次运行应用程序都会返回相同的伪随机信息.
If you don't seed, the same pseudo-random information is returned on each application run.
一些变化:
func rand2() bool {
return rand.Int31()&0x01 == 0
}
func rand3() bool {
return rand.Intn(2) == 0
}
这是不使用math/rand
软件包的有趣解决方案.它使用 select
语句:
And an interesting solution without using the math/rand
package. It uses the select
statement:
func rand9() bool {
c := make(chan struct{})
close(c)
select {
case <-c:
return true
case <-c:
return false
}
}
说明:
select
语句从可以继续进行而不会阻塞的情况中选择一种 random 情况.由于从封闭渠道接收可以立即进行,因此将随机选择这两种情况之一,然后返回true
或false
.请注意,但这并不是完全随机的,因为这不是select
语句的要求.
The select
statement chooses one random case from the ones that can proceed without blocking. Since receiving from a closed channel can proceed immediately, one of the 2 cases will be chosen randomly, returning either true
or false
. Note that however this is far from being perfectly random, as that is not a requirement of the select
statement.
也可以将通道移至全局变量,因此无需在每个调用中创建一个或关闭一个:
The channel can also be moved to a global variable, so no need to create one and close one in each call:
var c = make(chan struct{})
func init() {
close(c)
}
func rand9() bool {
select {
case <-c:
return true
case <-c:
return false
}
}
这篇关于我如何让函数在执行过程中随机返回true或false的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!