A function random_int_with_probability
that returns a random number within a range, where the chance to get a bigger value decreases linearly towards the maxima.
In the example below, the chance decreases by 10%, meaning to you will have guaranteed 100% chance to at least get 1
, then have 90% to get 2
, 3
at 80% and so on.
Of course to get an exact number the probability has to be calculated using the rectangular distribution formula (correct me if I am wrong).
As an optimization I would be happy to actually use a mathematical expression instead of the loop.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random_int (int minValue, int maxValue)
{
return minValue + (int)rand() % (maxValue - minValue);
}
int random_bool_with_probability (double percentage)
{
return ((rand() % 100) <= percentage);
}
int random_int_with_probability (int minValue, int maxValue, int progressionIncrement)
{
int pi = 100;
double mi = 0;
for(mi = minValue; mi <= maxValue; mi++)
{
int p = random_bool_with_probability(pi);
if(p == 0)
break;
pi -= progressionIncrement;
}
return random_int(minValue, mi);
}
/* Test */
int main (void)
{
int counter = 0;
srand(time(NULL));
while(counter < INT_MAX-1)
{
int stat = random_int_with_probability(1, 10, 10);
counter++;
if(stat >= 9)
break;
}
printf("You pulled out the maximum value of 9 at attempt %i\n", counter);
return 0;
}