List::Util::WeightedChoice - Perl extension to allow for nonnormalized weighted choices


List-Util-WeightedChoice documentation  | view source Contained in the List-Util-WeightedChoice distribution.

Index


NAME

Top

List::Util::WeightedChoice - Perl extension to allow for nonnormalized weighted choices

SYNOPSIS

Top

  use List::Util::WeightedChoice qw( choose_weighted );
  my $choices = ['Popular', 'Not so much', 'Unpopular'];
  my $weights = [ 50, 25, 1] ;
  my $choice = choose_weighted( $choices, $weights );




  my $complexChoices = [ 
    {val=>"Not so much", weight=>2},
    {val=>"Popular", weight=>50},
    {val=>"Unpopular", weight=>1},
    ];

  $choice = choose_weighted($complexChoices, sub{ $_[0]->{weight} } );




DESCRIPTION

Top

Just one function, a simple means of making a weighted random choice

The implementation uses rand to calculate random numbers.

EXPORT

None by default.

choose_weighted

 choose_weighted ($object_Aref, $weights_Aref )

or choose_weighted ($object_Aref, $weights_codeRef )

In the second case, the coderef is called on each object to determine its weight;

SEE ALSO

Top

List::Util

CAVEATS

Top

TODO: object-oriented module to implement fast re-picks with binary searches.

OO-interface ought to allow for other sources of randomness;

This currently does a linear search to find the winner. It could be made faster

AUTHOR

Top

Danny Sadinoff, <lt>danny-cpan@sadinoff.com>

COPYRIGHT AND LICENSE

Top


List-Util-WeightedChoice documentation  | view source Contained in the List-Util-WeightedChoice distribution.