in reply to Weighted random selection
use List::Util qw(sum); my $total = sum values %$group; my $picked; for (keys %$group){ if (rand() < $group->{$_} / $total){ $picked = $_; last; } # update: I forgot this line: $total -= $group->{$_}; # without this line items later in the hash are chosen # too seldom, and you might chose none at all. Very bad. }
I somehow think it's not entirely fair, but I can't get a straight thought on stochastic at this time (0:30 AM here), maybe I can think of a prove (or disprove) tomorrow.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Weighted random selection
by cosmicperl (Chaplain) on Jul 29, 2008 at 00:02 UTC | |
|
Re^2: Weighted random selection
by jethro (Monsignor) on Jul 28, 2008 at 23:31 UTC |