dongrang2140 2017-06-23 10:26
浏览 2356
已采纳

我怎样才能让函数随机返回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

How can I return a random boolean?

  • 写回答

4条回答 默认 最新

  • dpbe81245 2017-06-23 10:32
    关注

    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.

    A very simple example using rand.Float32() of the math/rand package:

    func rand1() bool {
        return rand.Float32() < 0.5
    }
    

    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())
    }
    

    This is mentioned in the package doc of math/rand:

    Use the Seed function to initialize the default Source if different behavior is required for each run.

    If you don't seed, the same pseudo-random information is returned on each application run.

    Some variations:

    func rand2() bool {
        return rand.Int31()&0x01 == 0
    }
    
    func rand3() bool {
        return rand.Intn(2) == 0
    }
    

    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
        }
    }
    

    Explanation:

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?