問題描述
我有一個結(jié)構(gòu)數(shù)組,結(jié)構(gòu)中的一個字段是浮點數(shù).我想選擇一種結(jié)構(gòu),其中選擇它的概率與浮點數(shù)的值有關(guān).即
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
與隨機數(shù)進行比較,更改每個 s 的隨機數(shù)?即
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
這篇關(guān)于用于從每個元素具有不同概率的列表中進行選擇的 C++ 函數(shù)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!