in reply to Randomize elements among several arrays, while maintaining original array sizes.
Here's a neat use of Perl's aliasing of @_.
#! perl -slw use strict; ## Shuffle an array in place; sub shuffle { my $ref = @_ == 1 ? $_[ 0 ] : \@_; my $n = @$ref; for( 0 .. $#$ref ) { my $p = $_ + rand( $n-- ); my $t = $ref->[ $p ]; $ref->[ $p ] = $ref->[ $_ ]; $ref->[ $_ ] = $t; } return unless defined wantarray; return wantarray ? @{ $ref } : $ref; } my @a = 'a' .. 'c'; my @b = 1 .. 4; my @c = 'A' .. 'E'; shuffle( @a, @b, @c );; print "A:= [ @a ]\nB:= [ @b ]\nC:= [ @c ]"; __END__ c:\test>junk8 A:= [ c b D ] B:= [ 4 A 3 B ] C:= [ E 2 a 1 C ]
Notice how after the shuffle, the elements of the arrays have been intermixed in the 3 arrays, but each knows how big it is. This is because @_ gets aliased to the elements of all 3 arrays.
Thus, by shuffling @_ within the sub, we are shuffling the elements of all 3 arrays at the same time.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Randomize elements among several arrays, while maintaining original array sizes.
by Roy Johnson (Monsignor) on Aug 01, 2008 at 19:07 UTC | |
|
Re^2: Randomize elements among several arrays, while maintaining original array sizes.
by BioNrd (Monk) on Aug 01, 2008 at 17:04 UTC | |
by blazar (Canon) on Aug 05, 2008 at 21:22 UTC |