in reply to Re: Weighted random selection
in thread Weighted random selection
rand() is only called once. No array is made. Straight forward if and a last to drop out once found. Haven't tested for efficiency but I'm guessing it's pretty good.use List::Util qw(sum); my $total = sum values %$group; my $rnd = rand( $total ); my $runningtot = 0; foreach ( keys %$group ) { if ( $rnd > $runningtot && $rnd <= ( $runningtot + $group->{$_} ) +) { $picked = $_; last; }#if $runningtot += $group->{$_}; }#foreach
|
|---|