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