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

perl -le 'while(@list<3){$n=int(10*rand)+1;push @list,$n unless grep{$n==$_}@list}print for @list;'

Update: Even better:

perl -le '@list=1..10;for(1..3){push @list,shift @list for 1..rand 10; + print pop @list}

Replies are listed 'Best First'.
Re: Re: Select three random numbers between 1..10
by waswas-fng (Curate) on Mar 16, 2004 at 21:34 UTC
    perl -le '@n=(1..10);while(@l<3){push@l, splice@n,int rand@n,1}print for@l'


    -Waswas
      or... perl -le '@l=sort{rand$_<=>rand$_}(1..10);print for@l[0..2]]'


      -Waswas
        perl -le '@l=sort{rand$_<=>rand$_}(1..10);print for@l[0..2]'
        In older Perls, it's not garanteed to give any meaningful results - in fact, perl might as well segfault. In modern Perls, about all that's garanteed is that perl won't segfault, and perl won't internally get corrupted. I'm not at all convinced that the above code produces fair results. Here's a test with a smaller array that strongly suggests your algorithm isn't fair:
        #!/usr/bin/perl use strict; use warnings; no warnings qw /syntax/; my @array = (1 .. 4); my %count; my $mult = 10_000; for (1 .. 24 * $mult) { my @t = sort {rand 1 <=> rand 1} @array; $count {"@t"} ++; } foreach my $key (sort keys %count) { printf "%5d: %s\n" => $count {$key}, $key } __END__ 15063: 1 2 3 4 15069: 1 2 4 3 7419: 1 3 2 4 7615: 1 3 4 2 7602: 1 4 2 3 7606: 1 4 3 2 14978: 2 1 3 4 14923: 2 1 4 3 7497: 2 3 1 4 7460: 2 3 4 1 7558: 2 4 1 3 7401: 2 4 3 1 7485: 3 1 2 4 7484: 3 1 4 2 7585: 3 2 1 4 7577: 3 2 4 1 14876: 3 4 1 2 14968: 3 4 2 1 7467: 4 1 2 3 7544: 4 1 3 2 7461: 4 2 1 3 7477: 4 2 3 1 14853: 4 3 1 2 15032: 4 3 2 1

        Abigail