How to retrieve a row, biased by populatity?

Yitzchak Scott-Thoennes sthoenna at gmail.com
Wed Aug 22 03:35:55 BST 2012


The single pass approach, as given in perlfaq "How do I select a
random line from a file?" adapts to work here too.

my $total_weight = 0;
my $selected;
while ( my $record = get_next_record() ) {
    my $weight = weight($record);
    $total_weight += $weight;
    $selected = $record if $weight > $total_weight * rand;
}

Weights can be integers or floating point, but must be >= 0.  A record
is guaranteed to be selected unless all weights are 0 or there are no
records.


More information about the london.pm mailing list