I've been using this for some time to return either true
or false
when building fake seed data. Just wondering if anybody has a better, more succinct or verbose way of returning either true
or false
.
rand(2) == 1 ? true : false
Use random. getrandbits() to get a random boolean value Call random. getrandbits(k) with k set to 1 to get a single random bit. A bit is either 0 (representing False ) or 1 (representing True ). Use bool() to convert the random bit into a bool.
bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);
The Boolean object represents a truth value: true or false .
The nextBoolean() method of Random class returns the next pseudorandom, uniformly distributed boolean value from the random number generator's sequence.
A declarative snippet using Array#sample:
random_boolean = [true, false].sample
How about removing the ternary operator.
rand(2) == 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With