I need help writing a bit of code that makes something have a 5% chance of happening, and then if it doesn't happen, it needs to have a boolean variable equivalent to true. Can anyone help me?
When you throw a dice, you can get any of the six faces. What is the chance to get a 6? ~17% In other words, you can get any number from a throw, but getting a 6 happens with a 17% chance.
Throw a "dice" that has enough faces -- N -- and you get numbers from 0 to N-1. If 1/N is 5%, then getting one particular value has the chance of 5%.
For percentages I usually generate a floating point number between 0-1 and compare the number to the desired percentage.
Using C++11 <random> lib:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// elsewhere:
std::mt19937 rng;
// percentage checker
bool randPercentageCheck(double pct)
{
staticconst std::uniform_real_distribution<double> dist(0,1); // <- random number between 0-1
return (dist(rng) < pct); // <- returns true of the generated number is less than our given
// percentage
}
// usage
hit = randPercentageCheck( 0.05 ); // check for 5%
With the old style rand() function, it's not as convenient to work with floating points... so the easiest way there is to do something like this:
hit = (rand() % 100) < 5;
Or if you want to turn that into a reusable function: