in reply to removing the goto
You already have good solutions, I'll just suggest an approach that works very similarly but is spelled out in different style.
# I'll call @weighteddiv "@input" here, and $maxclients "$choose_count +". { my %selected_set; my $choose_one = sub { $selected_set{ rand(@input) } = 1) }; $choose_one->() while keys %selected_set < $choose_count; my @selected = @input[ keys %selected_set ]; }
This uses a new variable to remember which indexes had already been selected. It doesn't shuffle the input so it's less expensive up front but risks running forever if the random selections are unlucky (or indeed if you ask for more selections than the input contains). In practical terms, this means you should choose this strategy when @input is large and $choose_count is small.
You can of course inline the choose_one function, since it's so simple and only used once. I put it there for clarity.
Note that your rand never selected the last element of the input.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: removing the goto
by TimToady (Parson) on Jun 02, 2007 at 17:00 UTC | |
by gaal (Parson) on Jun 02, 2007 at 20:27 UTC |
In Section
Seekers of Perl Wisdom