Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I let a function randomly return either a true or a false in go

Tags:

random

boolean

go

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?

like image 495
Mister Verleg Avatar asked Jun 23 '17 10:06

Mister Verleg


People also ask

How do you randomize true or false in Python?

The random. random() function generated a random floating number between 0 and 1. The generated number is compared with 0 by using the if() function. If the generated number is greater than 0, the used method will return True as output, else it will return False.


2 Answers

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
    }
}
like image 192
icza Avatar answered Nov 11 '22 01:11

icza


This function returns true if the random integer is even else it returns false:

func randBool() bool{
    return rand.Int() % 2 == 0
}
like image 38
adjan Avatar answered Nov 10 '22 23:11

adjan