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?
Problem 1: Generating a random number with go produces the same result on each call.
Here's another one liner, requires no random number generation/seeding etc., fairly simple :
Edited after @icza's comments : time.Now() is supposed to return time with nanosecond accuracy, but on Windows 10 Pro 64-bit (and I tried with go 1.8 & it may be true with other Windows OS too) it always returns time with lesser precision (probably micro second), rounding off the result so that it'll end with xxxxx..00 and hence this function will return true always. I have modified the function so one can see the result also. Works fine on Linux & probably should on other Unix OS'es too. So either use this function only after testing or better don't use if you need to deploy on a Windows system. It's unfortunate and hard to believe this, but it's a reality, bad Windows implementation. Thanks @icza for pointing out.
The easiest way will be to create a random number and then take its modulus of 2. Then if it is 0 the return true and if it is 1 then return false.
You need some kind of random information, and based on its value, you can return
true
in half of its possible cases, andfalse
in the other half of the cases.A very simple example using
rand.Float32()
of themath/rand
package:Don't forget to properly seed the
math/rand
package for it to be different on each app run usingrand.Seed()
: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.
Some variations:
And an interesting solution without using the
math/rand
package. It uses theselect
statement: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 eithertrue
orfalse
. Note that however this is far from being perfectly random, as that is not a requirement of theselect
statement.The channel can also be moved to a global variable, so no need to create one and close one in each call:
This function returns true if the random integer is even else it returns false: