views:

66

answers:

1

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};
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;
 }
}

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%
A: 

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())];
PigBen
Thanks, but I just decided to go with 1 / x. With {1,2,3}, it gives {50%, 33%, 16%}... which works for what I want. A key focus was speed, so memory allocation was something I wanted to avoid as best I could.
Daniel