in reply to Generating 2 unique random integers (So I can't pop a list...)
update: splice can be an expensive operation as it has to move all the elements inside the array from the insertion point upwards (complexity O(N)).# my @numbers = (1..10); oops, thanks RMGir! my @a = (1..10); my $r1 = splice @a, rand(@a), 1; my $r2 = splice @a, rand(@a), 1;
A more efficient approach is:
sub pop_any (\@) { my $a = shift; my $r = int rand(@$a); @{$a}[$r, 0] = @{$a}[0, $r] if $r; shift @$a } my @a = (1..10); my $r1 = pop_any @a; my $r2 = pop_any @a;
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Generating 2 unique random integers (So I can't pop a list...)
by RMGir (Prior) on Sep 11, 2008 at 12:38 UTC | |
| A reply falls below the community's threshold of quality. You may see it by logging in. |