用于从每个元素具有不同概率的列表中进行选择的 C++ 函数

2021-12-21 00:00:00 random probability c++

我有一个结构数组,结构中的一个字段是浮点数.我想选择一种结构,其中选择它的概率与浮点数的值有关.即

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];

决定选择哪个的最快方法是什么?有这个功能吗?如果我知道所有概率字段的总和(注意它不会是 1),那么我可以遍历每个 s 并将 probability/total_probability 与随机数进行比较,更改每个 s 的随机数?即

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)...

推荐答案

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

相关文章