Search code examples
c++randomprobability

Random numbers with different probabilities


I need to randomly determine a yes or no outcome (kind of a coin flip) based on a probability that I can define (.25, .50, .75).

So for example, I want to randomly determine yes or no where yes has a 75% chance of being chosen. What are my options for this? Is there a C++ library I can use for this?


Solution

  • You can easily implement this using the rand function:

    bool TrueFalse = (rand() % 100) < 75;
    

    The rand() % 100 will give you a random number between 0 and 100, and the probability of it being under 75 is, well, 75%. You can substitute the 75 for any probability you want.