Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Weighted random numbers generator

by Limbic~Region (Chancellor)
on Mar 13, 2003 at 22:06 UTC ( [id://242860]=note: print w/replies, xml ) Need Help??


in reply to Weighted random numbers generator

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

  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Domain Nodelet?
    Node Status?
    node history
    Node Type: note [id://242860]
    help
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this?Last hourOther CB clients
    Other Users?
    Others learning in the Monastery: (5)
    As of 2024-04-24 22:13 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      No recent polls found