The Perl Toolchain Summit needs more sponsors. If your company depends on Perl, please support this very important event.

NAME

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

SYNOPSIS

  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

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

List::Util

CAVEATS

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

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

COPYRIGHT AND LICENSE

Copyright (C) 2009 by Danny Sadinoff

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.