my @arr=(1..20);
for(1..200)
{
$random_position=int(rand($#arr));
$var=splice(@arr, $random_position, 1);
push(@arr, $var);
}
foreach (@arr)
{print "$_\n";}
Cheers - L~R
Why don't people read FAQs any more?
How do I shuffle an array randomly?
"The first rule of Perl club is you do not talk about
Perl club."
-- Chip Salzenberg
Why don't people read FAQs any more?Maybe because they don't know how? :)
perldoc -q randomor one could take a look in the Perl FAQ here at PM, sneakily called [id://1843] (array->how do I shuffle).
-- Hofmator
Hi [tamaguchi], Try this,
use strict; use warnings; use Data::Random qw(:all); my @set = (1..200); my @random_set = rand_set( set => \@set, size => $#set ); $,="\n"; print @random_set;
Regards,
Velusamy R.
You need to know this: The shuffle() routine implemented in List::Util is a fair shuffle; It is an implementation of the fisher-yates shuffle. Other recipies such as yours are not certain to be 'fair'. I don't know if yours is biased or not, but why leave it to chance when there's a perfectly good alternative built into a module that comes with Perl? I do know that it is very easy to get it wrong when writing an unbiased shuffle routine. Good thing someone included a fair, unbiased shuffle in List::Util
Dave
blokhead
If this is for a class project or a nuclear power plant I wouldn't do it this way:
@a = (0..20);$,="\n";
for(0..200){$b=shift @a;push @a,(int rand 2)?($b,shift @a):(shift@a,$b)}
print @a;
I recommend a look at the node 1824 section of Categorized Questions and Answers:
Super Search is your friend:
... and so on.
HTH,
The best way to unsort an array? Sort it!!
@a=0..20;$,=" ";
print sort {1-int rand 3} @a;
OK, I couldn't resist golfing it.
perlmonks.org content © perlmonks.org and Anonymous Monk, blokhead, davido, davorg, Hofmator, Limbic~Region, planetscape, Samy_rio, starbolin, tamaguchi
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03