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++ 函数
基础教程推荐
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
