in reply to Picking unique element in random from a array

It should work, I hope that it does not need explanation:
#!/usr/bin/perl my $n = 1000; my $cnt = 10; my %ret; for (my $i = 0; $i < $cnt; $i++) { my $r = int(rand()*$n); $r++ while exists $ret{$r}; $ret{$r} = undef; $n--; } print "$cnt random indexes:\n"; foreach (keys %ret) { print "$_\n"; }

Replies are listed 'Best First'.
Re^2: Picking unique element in random from a array
by pajout (Curate) on Aug 10, 2006 at 13:19 UTC
    I am sorry, I'v made a mistake:

    my $n = 1000; my $cnt = 10; my @ret; for (my $i = 0; $i < $cnt; $i++) { my $r = int(rand()*$n); my $j = 0; while ($j <= $r) { $r++ if defined $ret[$j]; $j++; } $ret[$r] = 1; $n--; } print "$cnt random indexes:\n"; for (my $i = 0; $i < $n+$cnt; $i++) { print "$i\n" if $ret[$i]; }
    As you can see, the repaired algorithm does ~ $n*$cnt cycles. It is too naive. Therefore, it should be better to use some previously adviced libraries.