in reply to How to not print the same random number

The following should achieve pretty random results within the constraints you asked for - 10 unique numbers from 1-10 sorted randomly.
@arr = 1..10; randomize(\@arr); print "@arr"; sub randomize { my ($p, $size, $swap, $key); $p = $_[0]; $size = $#$p; for (0..($size-1)) { $swap = int rand($size - $_ + 1) + $_; $key = $p->[$_]; $p->[$_] = $p->[$swap]; $p->[$swap] = $key; } }

Replies are listed 'Best First'.
Re^2: How to not print the same random number
by GrandFather (Saint) on Mar 05, 2006 at 21:17 UTC

    You can eliminate the manifest temporary by:

    ($p->[$_], $p->[$swap]) = ($p->[$swap], $p->[$_]);

    Note though that it is slower:

    use strict; use warnings; use Benchmark qw(cmpthese); my @arr = 1..2; cmpthese (-1, { temp => sub {my $temp = $arr[0]; $arr[0] = $arr[1]; $arr[1 +] = $temp;}, swap => sub {($arr[0], $arr[1]) = ($arr[1], $arr[0]);}, } ); Rate swap temp swap 1381331/s -- -43% temp 2425611/s 76% --

    DWIM is Perl's answer to Gödel
A reply falls below the community's threshold of quality. You may see it by logging in.