http://qs321.pair.com?node_id=1098451

vagabonding electron has asked for the wisdom of the Perl Monks concerning the following question:

Dear All,

I read with interest the following thread on SO http://stackoverflow.com/questions/25285792/generate-all-permutations-of-a-list-without-adjacent-equal-elements and since I do have a use case for this I tried to make it in perl. I need only one perfectly shuffled array so I did not deal with the generation of permutations.

Update: The task in the above thread was: how to shuffle the list so that equal elements are never (or as seldom as possible) adjacent.

Here is the code which seems to correctly manage all the examples of the above mentioned thread. What do you think about it?

Thank you in advance!

Update: sample runs:

C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 0 0 1 0 0 1 0 1 0 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 0 1 1 0 1 1 1 0 1 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 1 2 3 3 2 2 1 1 2 3 3 2 2 1 1 2 1 3 2 3 2 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 3 2 1 2 1 3 2 3 2 1 2 1 3 2 1 2 1 3 2 3 2 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 1 3 3 3 3 1 1 1 3 3 3 3 1 1 3 1 3 1 3 1 3 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 1 1 1 2 3 1 1 1 2 3 1 2 1 3 1 C:\Perl_516_portable>perl D:\PM\mostly_shuffled_008.pl 1 1 1 2 3 3 2 2 + 1 1 1 1 2 3 3 2 2 1 1 2 1 2 1 3 1 3 2

The code:

#!/perl use strict; use warnings FATAL => qw(all); use List::MoreUtils qw( zip ); die "Where is an array?\n" unless @ARGV; my @array = @ARGV; print "@array\n"; my $aa = unsort([@array]); print "@$aa\n"; sub unsort { my $aref = shift; my @tmp; my %nums; @tmp[0 .. $#$aref] = (undef) x $#$aref; @$aref = sort {$a <=> $b} @$aref; @nums{@$aref} = @tmp; return $aref if scalar keys %nums == 1; my $half = int(($#$aref + 2 )/ 2 ); if ( scalar keys %nums == 2 ) { if ( $aref->[$half - 1] == $aref->[$#$aref] ) { @$aref = ( @$aref[$half .. $#$aref], @$aref[0..$half-1] ); @$aref[$half-1, $#$aref] = @$aref[$#$aref,$half-1]; } } else { for my $i ( 0 .. $half - 1 ) { last if $i + $half > $#$aref; if ( $aref->[$i] == $aref->[$i + $half-1] ) { @$aref = ( @$aref[$i .. $#$aref], @$aref[0..$i-1] ); } } } my @first = @$aref[0..$half-1]; my @second = @$aref[$half .. $#$aref]; #################### An ugly hack for for odd-size arrays. if ( scalar @$aref % 2 ) { push @second, 0; } @tmp = zip @first, @second; if ( scalar @$aref % 2 ) { pop @tmp;} #################### @$aref = @tmp; return $aref; }