go ahead... be a heretic | |
PerlMonks |
Re: Randomly choosing from a set of alternatives with varying popularityby LanX (Saint) |
on Mar 28, 2022 at 01:23 UTC ( [id://11142437]=note: print w/replies, xml ) | Need Help?? |
> To favor the popular, you choose a random number N from 0 to 549, then traverse the set of animals, subtracting each one's popularity from N until N goes negative, and that's the animal you choose. I don't think that's a good idea. More than 80% of your random numbers will be bigger than 100, which means none will be picked. This also explains why you have problems inverting this "solution". Furthermore a linear search in the hash won't be truly random, because the hash order is fixed within the duration of a run. This will result in a disproportionate representation of the early entries. Solution is easy: sort the N entries and chose a modified random function which favors one end of the range, like $i = int $N * rand() ** $e and $j = $N - 1 - $i for index in your sorted list. The way you chose $e > 1 will decide about the degree of bias ( $e=1 means no bias) Just test the distribution of the indices:
In this example the first 10% are more than 10 times more likely to be picked than the last 10%. Of course YMMV about the distribution you prefer, but the basic idea is the same.
Cheers Rolf
In Section
Seekers of Perl Wisdom
|
|