Skip to content

Instantly share code, notes, and snippets.

@AdamBrouwersHarries
Created December 19, 2013 20:40
Show Gist options
  • Save AdamBrouwersHarries/8045920 to your computer and use it in GitHub Desktop.
Save AdamBrouwersHarries/8045920 to your computer and use it in GitHub Desktop.
Roulette wheel selection
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//just a quick method to print the thresholds of each of the "roulette cells"
void print_thresholds(float* random_inputs, int input_len)
{
float p_acc=0;
for (int i = 0; i < input_len; ++i)
{
printf("I:%2d L: %3f H: %3f\n",i,p_acc, p_acc+random_inputs[i]);
p_acc+=random_inputs[i];
}
printf("-----------\n");
}
//actually does the roulette method
int select_random(float* random_inputs, int input_len)
{
//find the probability sum
float p_total = 0;
for (int i = 0; i < input_len; ++i)
{
p_total+=random_inputs[i];
}
printf("Total prob: %f\n", p_total);
float roulette_val = ((float)(rand()%10000)/10000)*p_total;//generate a value in range [0,p_total]
printf("Roulette_val: %f\n", roulette_val);
int roulette_index = 0;
while(roulette_val>=0 && roulette_index<=input_len) //second part shouldn't really be necessary...
{
printf("roulette_val: %f | ",roulette_val);
//subtract the probability rejected
roulette_val = roulette_val-random_inputs[roulette_index];
//move on to next value
roulette_index++;
}
//decrement because of the ++ in the while loop
roulette_index--;
printf("\nGot index: %d\n",roulette_index);
printf("----------------\n");
return roulette_index;
}
int main(int argc, char const *argv[])
{
//seed the random number generator with the time
time_t tmr;
srand(time(&tmr));
//generate the array of random values
float r_values[] = {0.4,0.2,0.5,0.6,0.7,0.1};
print_thresholds(r_values, 6);
select_random(r_values,6);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment