List::Util::WeightedChoice - Perl extension to allow for nonnormalized weighted choices
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} } );
Just one function, a simple means of making a weighted random choice
The implementation uses rand to calculate random numbers.
None by default.
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;
List::Util
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
Danny Sadinoff, <lt>danny-cpan@sadinoff.com>
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.
To install List::Util::WeightedChoice, copy and paste the appropriate command in to your terminal.
cpanm
cpanm List::Util::WeightedChoice
CPAN shell
perl -MCPAN -e shell install List::Util::WeightedChoice
For more information on module installation, please visit the detailed CPAN module installation guide.