XP is just a number | |
PerlMonks |
Re: Weighted random numbers generatorby Zaxo (Archbishop) |
on Mar 13, 2003 at 18:05 UTC ( [id://242772]=note: print w/replies, xml ) | Need Help?? |
You can swap memory for time to do this in O(1). Populate an array with your values in the distribution you want, and select a random index. Your example, ( 1, 1.25, 3.6, 2), is ( 20/20, 25/20, 72/20, 40/20), so: If time is not an issue, your method is fine, except that < is probably better than <= in the comparisons. That is because rand() returns a number less than one. After Compline,
In Section
Seekers of Perl Wisdom
|
|