Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

You might want to edit your post to clarify that weight does not affect the probability of a given selection.

Two ideas

You could pre-calculate (perhaps write to data files if there are many) all possible items and their strength/weight values. If your list of possible weight values is dense (few skipped values) put an array of items at each weight at a coresponding index in a master array. So:

my @items = ( # 0 [ 'sword', 'mace', 'turtle' ], # 1 [ '+1 sword', '+1 mace', '+1 turtle' ], # 2 [ 'frost sword', 'frost mace', 'frost turtle', 'flame sword', 'flame mace', 'flame turtle' ], ... );

If the set of weights is sparse, you might use a hash instead.

Then if you want to select a random item of weight 3-5, you can do:

my @in_range = map @{$items[$_]}, 3..5; my $item = $in_range[ int rand( @in_range ) ];

Another way, would be:

  1. Pick a random weight value in your range. eg 7
  2. Prefix list is sorted by weight, and starts with an entry for ['' => 0].
  3. Find last prefix with weight less than or equal to weight. Eg. Pointy (6)
  4. Pick Random Prefix up to max prefix from last step. eg. Acid (4)
  5. Set plus value equal to desired weight - prefix weight. Eg. Plus = 7 - 4 = 3
  6. Result: Acid +3 Sword


TGI says moo


In reply to Re: Algorithm Help by TGI
in thread Algorithm Help by dreadpiratepeter

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: (3)
As of 2024-04-24 18:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found