Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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


    In reply to Re: Weighted random numbers generator by Limbic~Region
    in thread Weighted random numbers generator by spurperl

    Title:
    Use:  <p> text here (a paragraph) </p>
    and:  <code> code here </code>
    to format your post; it's "PerlMonks-approved HTML":



    • Are you posting in the right place? Check out Where do I post X? to know for sure.
    • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
      <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
    • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
    • Want more info? How to link or How to display code and escape characters are good places to start.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Domain Nodelet?
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this?Last hourOther CB clients
    Other Users?
    Others chilling in the Monastery: (4)
    As of 2024-04-19 16:55 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found