spurperl,
I have only briefly read the other replies, but I believe my solution may be unique. If it isn't, then I apologize.
First let me solve your overly simplistic example, then give you the logic behind a more general solution:
For example, I'd like to decide between 0, 1 and 2 randomly, with 0 and 1 having an equal chance to be chosen, and 2 having a chance that is twice higher.
This can be reduced to generating a random number between 1 and 4 and then checking the results.
If the number is 1, then choose 0
if the number is 2 then choose 1
If the number is 3 or 4 then choose 2
The more general approach to this is to calculate how many elements are required to cover the entire range, and then set up the range logic to check the results.
I haven't provided any code because it is pretty straight forward, but if you would like to see some code that can generate the weighting dynamically - let me know as it less straight forward (but still not too difficult).
Hope this helps - L~R
Update: Just realized this is my 100th post - woo hoo
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.