In order to make this happen, you should also make an array to define for each element what the probability is that it gets picked. For instance, you could use the array {0.25, 0.4, 0.1, 0.05, 0.2}
. Make sure that the total probability is 1. Now, we generate a random float between 0 and 1. If the number falls between [0, 0.25]
, then we pick the first element. If the element falls between [0.25, 0.65]
, we pick the second element. Every time the interval is exactly the size of the element in the probabilities array that you define. This way we ensure that each element has exactly the probability of being picked that you define in your array.
The following function random_element_index
accomplishes exactly that:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define LENGTH 5
int random_element_index(float* probs) {
// This line generates a random float between 0 and 1
float random = (float)rand() / (float)RAND_MAX;
float sum = 0;
for (int i = 0; i < LENGTH; i++) {
sum += probs[i];
if (random < sum)
return i;
}
return -1;
}
int main() {
srand(time(NULL));
const char *yes[LENGTH] = {"one", "two", "three", "four", "five"};
float probabilities[LENGTH] = {0.25, 0.4, 0.1, 0.05, 0.2};
int index = random_element_index(probabilities);
printf("%s\n", yes[index]);
return 0;
}
If you're not convinced, here is a function you could use to see it in action:
void test_random() {
float probabilities[LENGTH] = {0.25, 0.4, 0.1, 0.05, 0.2};
int test[LENGTH] = {0, 0, 0, 0, 0};
for (int i = 0; i < 10000; i++)
test[random_element_index(probabilities)]++;
for (int i = 0; i < LENGTH; i++)
printf("%d\n", test[i]);
}