Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function for picking from a list where each element has a distinct probability

I have an array of structs and one of the fields in the struct is a float. I want to pick one of the structs where the probability of picking it is relative to the value of the float. ie

struct s{
  float probability;
  ...
}

s sArray[50];

What is the fastest way to decide which s to pick? Is there a function for this? If I knew the sum of all the probability fields (Note it will not be 1), then could I iterate through each s and compare probability/total_probability with a random number, changing the random number for each s? ie

if( (float) (rand() / RAND_MAX) < probability)...
like image 480
Stuart Avatar asked Apr 15 '10 23:04

Stuart


1 Answers

float p = (rand() / static_cast<float>(RAND_MAX)) * total_probability;
s* current = &sArray[0];
while ( (p -= current->probability) > 0)
    ++current;
// `current` now points to your chosen target
like image 80
rlbond Avatar answered Sep 28 '22 09:09

rlbond