C++ 随机选择最低权重
关于加权随机数有很多这样的问题,但它们都依赖于偏向最大数。我想偏向最低的 目前我的算法是随机加权,偏向更高的值C++ 随机选择最低权重,c++,random,math,C++,Random,Math,关于加权随机数有很多这样的问题,但它们都依赖于偏向最大数。我想偏向最低的 目前我的算法是随机加权,偏向更高的值 double weights[2] = {1,2}; double sum = 0; for (int i=0;i<2;i++) { sum += weights[i]; } double rand = urandom(sum); //unsigned random (returns [0,sum]) sum = 0; for (int i=0;i<2;i++) {
double weights[2] = {1,2};
double sum = 0;
for (int i=0;i<2;i++) {
sum += weights[i];
}
double rand = urandom(sum); //unsigned random (returns [0,sum])
sum = 0;
for (int i=0;i<2;i++) {
sum += weights[i];
if (rand < sum) {
return i;
}
}
这个怎么样:
template<typename InputIterator>
vector<int> generateWeightMap(InputIterator first, InputIterator last)
{
int value = 0;
vector<int> weightMap;
while(first != last)
{
while((*first)-- > 0)
weightMap.push_back(value);
++first;
value++;
}
return weightMap;
}
...later
int weights[] = {1,19,80};
vector<int> weightMap = generateWeightMap(weights, weights + 3);
int weighted_random = weightMap[urandom(weightMap.size())];
模板
vector GenerateWightMap(先输入计算器,后输入计算器)
{
int值=0;
向量权重图;
while(第一个!=最后一个)
{
而((*第一)-->0)
权重映射。推回(值);
++第一,;
值++;
}
返回权重图;
}
……以后
整数权重[]={1,19,80};
向量权重图=生成权重图(权重,权重+3);
int-weighted_random=weightMap[uradom(weightMap.size())];
这个怎么样:
template<typename InputIterator>
vector<int> generateWeightMap(InputIterator first, InputIterator last)
{
int value = 0;
vector<int> weightMap;
while(first != last)
{
while((*first)-- > 0)
weightMap.push_back(value);
++first;
value++;
}
return weightMap;
}
...later
int weights[] = {1,19,80};
vector<int> weightMap = generateWeightMap(weights, weights + 3);
int weighted_random = weightMap[urandom(weightMap.size())];
模板
vector GenerateWightMap(先输入计算器,后输入计算器)
{
int值=0;
向量权重图;
while(第一个!=最后一个)
{
而((*第一)-->0)
权重映射。推回(值);
++第一,;
值++;
}
返回权重图;
}
……以后
整数权重[]={1,19,80};
向量权重图=生成权重图(权重,权重+3);
int-weighted_random=weightMap[uradom(weightMap.size())];
谢谢,但我刚决定使用1/x。对于{1,2,3},它给出了{50%,33%,16%}。。。这是我想要的。一个关键的焦点是速度,所以我想尽量避免内存分配。谢谢,但我只是决定使用1/x。对于{1,2,3},它给出了{50%,33%,16%}。。。这是我想要的。一个关键的焦点是速度,所以内存分配是我想尽量避免的事情-(哎呀,我应该更仔细地考虑这个问题。)(哎呀,我应该更仔细地考虑这个问题。