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

[FWP] Weighted sampling



This is probably pretty trivial stuff, but I was surprised at how easy it 
turned out to be [and the 'surprise' counted as fun for me].

The problem: I have a weighted distribution that I need to sample from.  
I have an array of the 'weights' associated with each sample.  So I did:

my @dist ;
foreach my $i (0 .. $#weights)
{   push @dist, ($i) x $weights[$i] ; }

sub sample
{   return $dist[rand(@dist)] ; }

  /Bernie\
-- 
Bernie Cosell                     Fantasy Farm Fibers
mailto:bernie@fantasyfarm.com     Pearisburg, VA
    -->  Too many people, too few sheep  <--          

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