Perl Monk, Perl Meditation PerlMonks

Re: Algorithm Help

by TGI (Parson)
 on Jan 19, 2010 at 01:50 UTC ( #818089=note: 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

Create A New User
Node Status?
node history
Node Type: note [id://818089]
help
Chatterbox?
 [Lady_Aleena]: He never hears it. [marioroy]: Back in HighSchool, I came late to Gym class. There was a fellow who was picked last, no team wanted him for racketball. So it was us two against everybody. I looked at him in the eye and said to let your body loose and let the powers to be help us win. [marioroy]: We made it all the way to the end. The expience was magical. I not good at sports. Someone or thing was there. erix considers extracting a catalog ... [karlgoethebier]: marioroy: Racket ball is considered harmful, like Squash [marioroy]: Wait till folks see what MCE::Hobo can do in the upcoming release. Multiple instances, nested spawning, 3 levels, doesn't matter. it works on Windiows too. [Lady_Aleena]: I hate sites that tell me to turn ad-blocker off. They should know better. [marioroy]: s/Windiows/ Windows/ [Discipulus]: marioroy can you expand that Niagara's fall history? erix only sees fallen angels

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (8)
As of 2017-05-29 08:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?
My favorite model of computation is ...

Results (192 votes). Check out past polls.