Click to See Complete Forum and Search --> : random sorting on perl


npinelo
01-18-2004, 12:49 AM
Hi:

I have a script that have following code to sort results in order: @keepers=sort(@keepers); for reversal order I need to change it for following line: @keepers=reverse(sort(@keepers)); and works fine, my question is: what I need to write instead this line to get random sorting?

thank you in advance
npinelo

Jeff Mott
01-18-2004, 01:41 AM
random sorting?This phrase is sort of an oxymoron ;) I assume your question is simply how to randomize an array?sub shuffle {
my @a = splice @_;
for my $i (0 .. $#a) {
my $j = int rand @a;
@a[$i, $j] = @a[$j, $i];
}
return @a;
}

@shuffled_array = shuffle(@array);

npinelo
01-18-2004, 02:52 PM
Thanks a lot jeff I only needed to change last line of your code to be successfull sub shuffle {
my @a = splice @_;
for my $i (0 .. $#a) {
my $j = int rand @a;
@a[$i, $j] = @a[$j, $i];
}
return @a;
}

@keepers = shuffle(@keepers); now I can get random ordering :D

npinelo