Reading your post it struck me that you might have been trying not just to shuffle the elements within the nested arrays, and the order of the nested arrays with the top level, but possibly wanted to shuffle the elements between the arrays?
I seriously doubt that this is what you wanted to acheive, but it struck me as an interesting intellectual challenge none the less, and so I offer it on that basis:)
#! perl -slw use strict; use Data::Dumper; sub shuffleRefs (\@) { my $r=pop; $a = $_ + rand @{$r} - $_ and (${$r->[$_]}, ${$r->[$a]}) = (${$r->[$a]}, ${$r->[$_]}) for (0..$#{$r}); } sub shuffle2d { my @refs; push @refs, \( @$_ ) for @_; shuffleRefs @refs; return @refs; } my @data2d = ( [ qw[a b c d e] ], [ qw[1 2 3] ], [ qw[A B C] ], [ qw[I + II III IV] ] ); print "@$_" for @data2d; shuffle2d @data2d; print ''; print "@$_" for @data2d; __END__ C:\test>temp a b c d e 1 2 3 A B C I II III IV 1 a b e II d I c 2 C III A B 3 IV C:\test>
The interesting thing to note here is that whilst the elements have been shuffled between the nested arrays with proper statistical chance of any given element of any array ending up in any position in its original array or any other, but the size of each of the arrays can be different and the resultant arrays will remain the same size as they started out.
The trick is to shuffle a flattened array of references to the array elements and swap those elements through the references.
Now all I have to do is find a use for it:0
In reply to Re: How to Shuffle Multidimensional Arrays?
by BrowserUk
in thread How to Shuffle Multidimensional Arrays?
by Withigo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |