in reply to Select three random numbers between 1..10

push @num, splice(@array, int rand @array, 1);
Which will remove and return a random element from the array, there by, never picking the same number twice.

Replies are listed 'Best First'.
Re: Re: Select three random numbers between 1..10
by Limbic~Region (Chancellor) on Mar 16, 2004 at 21:19 UTC
    Paladin,
    Wow. That certainly is much neater than my solution. I knew there were likely canned solutions, but it seemed like a cool problem to solve:
    #!/usr/bin/perl use strict; use warnings; print "$_\n" for Get_Unique_Random(10 , 3); sub Get_Unique_Random { my ($max , $total) = @_; # Requires error checking obviously $total ||= 3; my @return; while ( @return < $total ) { my @list = ( 1 .. $max ); for my $seen ( @return ) { @list = grep { $_ ne $seen } @list; } push @return , $list[ (int rand $#list) + 1 ]; } return wantarray ? @return : \@return; }
    Cheers - L~R
Re: Re: Select three random numbers between 1..10
by hsinclai (Deacon) on Mar 18, 2004 at 02:46 UTC
    Honestly,
    push @num, splice(@array, int rand @array, 1);
    This totally made my day - the efficiency. In an extension of the original requirement, I needed to generate long fixed length strings from random elements in an array.. this is so much faster than what I was using.. I've no absolute requirement for total uniqueness, but it looks like no letter is being repeated in multiple runs of:
    #!/usr/bin/perl -w use strict; my $counter = "0"; my $randstring; my @testarray = ( 'a' .. 'z', 'A' .. 'Z', '0' .. '9' ); do { $randstring .= splice(@testarray, int rand @testarray,1); ++$counter; } until $counter == 62; print "\n\$randstring: $randstring\n\n";
    -hsinclai