[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [FWP] Probabilistic selection





On Thu, 19 Oct 2000, Paul Makepeace wrote:
>
>     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 }
>     }

Well, you could do it in one pass..

  my $sum = 0;
  my $which;
  while(my ($href, $weight) = each %target) {
      $which = $href if rand($sum += $weight) < $weight;
  }

-- 
Ilmari Karonen - http://www.sci.fi/~iltzu/
"And, should you resort to sticking a martini olive up their nose,
 implacable universal laws require that they'll _like_ that sort of
 thing."  -- Graydon in r.a.sf.c



==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe