http://www.perlmonks.org?node_id=158780


in reply to Re: Rolling a biased die
in thread Rolling a biased die

How about precaching a hash called %biasbase like this?

my $sum = 0; $biasbase{$_} = ($sum += $bias{$_}) foreach (reverse keys %bias);

And then iterate like this:

while( my($k,$v) = each %bias and not defined $rand){ $rand = $k if rand($biasbase{$k}) < $v; }

Does that make sense? That way you can bail out early.