Generate Random Boolean Probability

Dark Side picture Dark Side · Aug 13, 2014 · Viewed 53.2k times · Source

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

Answer

E. Moffat picture E. Moffat · Aug 13, 2014

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;