Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: random elements from array - new twist

by BrowserUk (Pope)
on Nov 05, 2002 at 09:01 UTC ( #210410=note: print w/replies, xml ) Need Help??


in reply to random elements from array - new twist

Another variation that's useful if the elements of the array itself are large and therefore costly to shuffle or perhaps more importantly, if its necessary to keep the array in it's original order.

Instead of shuffling the array, create and shuffle an array of indexes, then subset it to produce a slice from the real array.

#! perl -sw use strict; sub shufl (\@) { my $r=pop; $a = $_ + rand @{$r} - $_ and @$r[$_, $a] += @$r[$a, $_] for (0..$#{$r}); } my @array = qw(the quick brown fox jumps over the lazy dog and went st +raight into a puddle); my @indexes = (0..$#array); shufl(@indexes); my ($comp1, $comp2, $comp3, $comp4, $comp5) = @array[@indexes[0..4]]; print"$comp1, $comp2, $comp3, $comp4, $comp5\n"; __END__ #Ouput C:\test>210389.pl jumps, dog, a, the, fox C:\test>210389.pl a, the, lazy, brown, into C:\test>210389.pl and, quick, a, puddle, fox C:\test>210389.pl a, and, the, the, into C:\test>210389.pl dog, jumps, went, the, straight C:\test>210389.pl lazy, quick, and, into, fox C:\test>210389.pl the, went, the, brown, over C:\test>

Nah! Your thinking of Simon Templar, originally played by Roger Moore and later by Ian Ogilvy

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://210410]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (5)
As of 2020-10-31 21:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (291 votes). Check out past polls.

    Notices?