in reply to Generating 2 unique random integers (So I can't pop a list...)

you don't need to shuffle the full array, just splice two random elements:
# 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;
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)).

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
    I think you mean:
    my @numbers = (1..10); my $r1 = splice @numbers, rand(@numbers), 1; my $r2 = splice @numbers, rand(@numbers), 1;
    @a was confusing me...

    Mike
A reply falls below the community's threshold of quality. You may see it by logging in.