开发者

Selecting Randomly Lowest Weighted

开发者 https://www.devze.com 2023-01-20 21:09 出处:网络
There are plenty of SO questions on weighted random, but all of them rely on the the bias going to the highest number. I want to bias towards the lowest.

There are plenty of SO questions on weighted random, but all of them rely on the the bias going to the highest number. I want to bias towards the lowest.

My algorithm at the moment, is the randomly weighted with a bias towards the higher values.

double weights[2] = {1,2};
dou开发者_Python百科ble 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;
 }
}

How could I convert this to bias lower values? Ie I want in a 100 samples, the weights[0] sample to be chosen 66% of the time; and weights[1] 33% of the time (ie the inverse of what they are now).


Hand example for Omni, ref sum - weights[x] solution

Original:
1 | 1 | 1%
20 | 21 | 20%
80 | 101 | 79%

Desired:
1 | ? | 79%
20 | ? | 20%
80 | ? | 1%

Now sum - weights[i]

100(101 - 1) | 100 | 50%
81(101 - 20) | 181 | 40%
21(101 - 80) | 202 | 10%


How about this:

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())];
0

精彩评论

暂无评论...
验证码 换一张
取 消