C++ function for picking from a list where each element has a distinct 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
这篇关于用于从每个元素具有不同概率的列表中进行选择的 C++ 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:用于从每个元素具有不同概率的列表中进行选择的 C++ 函数


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01