Paul Makepeace <Paul.Makepeace@realprogrammers.com> 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, [snip] >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. Adapting the "choose a random line from a file" recipe from the Perl Cookbook: my $total = 0; while (my ($dest, $weight) = each %target) { $total += $weight; $where = $dest if rand($total) < $weight; } -- Sean McAfee mcafee@umich.edu print eval eval eval eval eval eval eval eval eval eval eval eval eval eval q!q@q#q$q%q^q&q*q-q=q+q|q~q:q? Just Another Perl Hacker ?:~|+=-*&^%$#@! -- Sean McAfee | GCS d->-- s+++: a28 C++ US+++ P+++$ L++ E- W+ N++ | | K w--- O? M- V-- PS+ PE Y+ PGP?>++ t+() 5++ X R+ | mcafee@ | tv+ b++ DI++ D+ G e++ h r---* y+>++ | umich.edu ==== Want to unsubscribe from Fun With Perl? Well, if you insist... ==== Send email to <fwp-request@technofile.org> with message _body_ ==== unsubscribe