Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

random - 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)...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...