Paul Makepeace wrote: > I have a specification of link destinations and their weighted > probabilities like so: > > my %target = ( > '/: _top' => 1, > 'index.amyl: _parent' => 3, > 'index.amyl: _self' => 15, > 'upload.amyl: _parent' => 1, > ); > > In other words, you go to index.amyl in target="_parent" with > probability 3 out of (1+3+15+1). The advantage of this scheme > is that you don't have to make anything add up to 1.0 or use > floating point, etc. > > I implemented this fairly straightforwardly as follows, > > my $sum = 0; $sum += $_ for values %target; > my $which = rand $sum; > my $where; > $sum = 0; > for my $href (keys %target) { > if ($which < ($sum += $target{$href})) { $where = $href; last } > } > > Any neater ways of doing this? Including perhaps, but not > limited to, a different probabilities specification. I.e. any > way of achieving the same goal. i don't know about "neater", but here's another way: my %target = ( '/: _top' => 1, 'index.amyl: _parent' => 3, 'index.amyl: _self' => 15, 'upload.amyl: _parent' => 1, ); my @keylist = map { ($_) x $target{$_} } keys %target; my $key = $keylist[rand @keylist]; -- Steve Lane <sml@zfx.com> ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe