Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate Random Boolean Probability

I only know how I can generate a random boolean value (true/false). The default probability is 50:50

But how can I generate a true false value with my own probability? Let's say it returns true with a probability of 40:60 or 20:80 etc...

like image 805
Dark Side Avatar asked Aug 12 '14 23:08

Dark Side


People also ask

How do you generate a random Boolean?

In order to generate Random boolean in Java, we use the nextBoolean() method of the java. util. Random class. This returns the next random boolean value from the random generator sequence.

How do you generate a random Boolean in C++?

Until now I used the following code to generate a random bool : bool randomBool() { return 0 + (rand() % (1 - 0 + 1)) == 1; } // In main. cpp time_t seconds; time(&seconds); srand((unsigned int) seconds);

How do you get random True False in C#?

Use the NextDouble() Method From C# Class Random The NextDouble() returns a random double value between 0.0 and 1.0 . So, we can add a separator at any place between these two numbers and divide the numbers generated into true or false based on a separation condition.


1 Answers

Well, one way is Random.Next(100) <= 20 ? true : false, using the integer value of NextInt to force your own probability. I can't speak to the true 'randomness' of this method though.

More detailed example:

Random gen = new Random(); int prob = gen.Next(100); return prob <= 20; 
like image 71
E. Moffat Avatar answered Sep 22 '22 18:09

E. Moffat