Search code examples
c#.netrandombooleanprobability

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


Solution

  • One way is checking that the return value of Random.Next(100) is less than your desired probability. I can't speak to the true 'randomness' of this method though.

    Proper example, using desired probability of 20%:

    Random gen = new Random();
    int prob = gen.Next(100);
    return prob < 20;