C ++函数用于从列表中挑选,其中每个元素具有不同的概率 [英] C++ function for picking from a list where each element has a distinct probability
问题描述
我有一个结构体数组,结构体中的一个字段是一个浮点数。我想选择一个结构体,其中选择它的概率是相对于float的值。即
struct s {
float probability;
...
}
s sArray [50];
最快的方法是决定选择哪一个?有这样的功能吗?如果我知道所有概率字段的总和(注意它不会是1),那么我可以迭代通过每个s,并与随机数比较 probability / total_probability
每个s的随机数?
if((float)(rand()/ RAND_MAX)< probability)...
解决方案
static_cast< float>(RAND_MAX))* total_probability;
s * current =& sArray [0];
while((p - = current-> probability)> 0)
++ current;
//`current`现在指向你选择的目标
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)...
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
这篇关于C ++函数用于从列表中挑选,其中每个元素具有不同的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!