Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: Efficiently selecting a random, weighted element

by xdg (Monsignor)
on Oct 15, 2006 at 13:23 UTC ( #578380=note: print w/replies, xml ) Need Help??


in reply to Re^2: Efficiently selecting a random, weighted element
in thread Efficiently selecting a random, weighted element

Like almost any algorithm, it all depends on the exact nature of the problem space.

One refinement, if you really want to consider splicing out high-weight elements, is to create your array in sorted order so that all your highest weight files are at the end of the array. That will decrease the amount of recalculation necessary if you choose to drop them.

In the extreme case, if the highest weight word is chosen, you just pop the last element of the array and decrease the word count and you're done. If the second highest weight word is chosen, you splice out that word and have only one index to recalculate. Etc.

-xdg

Code written by xdg and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.

  • Comment on Re^3: Efficiently selecting a random, weighted element

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (5)
As of 2019-12-10 02:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?