Think about Loose Coupling | |
PerlMonks |
Re: Weighted random numbers generatorby blokhead (Monsignor) |
on Mar 13, 2003 at 17:05 UTC ( [id://242751]=note: print w/replies, xml ) | Need Help?? |
I'm no probabalist, but your code seems on the ball to me. Here's an alternative method I use from time to time that doesn't require the creation of an additional accumulating-weight array:
I have found this algorithm easier to adapt for multiple selections, i.e., calling choose_weighted( [1.75, 2, 3.6, 4], 2 ) and getting back two (different) numbers randomly chosen with this weighting. However, once you start doing this, you have to modify the array of weights (each time you select an item, set its weight to zero and subtract accordingly from $total), which may be undesired here. Cheers, blokhead
In Section
Seekers of Perl Wisdom
|
|