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
In reply to Re^2: Weighted random selection
by cosmicperl
in thread Weighted random selection
by cosmicperl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |