http://www.perlmonks.org?node_id=24364


in reply to How can I improve this?

Okay, this and merlyn's permuations code has been ticking in the back of my mind. Finally out popped a neat way to find all of the unique permutations of a set of (possibly) non-unique elements. For example, all of the unique permutations of the letters "h e l l o". Which is what I needed for solving this problem.

So here is a script that, when given no arguments, solves the noted problem. When given arguments, it outputs all of the unique permutations of those arguments, in sorted order, without using extra memory to accumulate values or track context (not even recursing).

#!/usr/bin/perl -w use strict; exit main(); sub nextpermute(\@) { my( $vals )= @_; my $last= $#{$vals}; return "" if $last < 1; my $i= $last-1; # Find last item not in reverse-sorted + order: $i-- while 0 <= $i && $vals->[$i] ge $vals->[$i+1]; return "" if -1 == $i; # Complete reverse sort, done! @{$vals}[$i+1..$last]= sort @{$vals}[$i+1..$last] if $vals->[$i+1] gt $vals->[$last]; my $j= $i+1; # Find next item that will make us big +ger: $j++ while $vals->[$i] ge $vals->[$j]; @{$vals}[$i,$j]= @{$vals}[$j,$i]; return 1; } sub main { if( @ARGV ) { my @vals= sort @ARGV; do { print "@vals\n"; } until( ! nextpermute(@vals) ); return 0; } #OR# my @map= (2,1,0); for my $zero ( 0..5 ) { for my $one ( 0..5-$zero ) { my $two= 5-$one-$zero; my @val= ( (0)x$zero, (1)x$one, (2)x$two ); #OR# @val= ( (0)x$two, (1)x$one, (2)x$zero ); do { print "@val\n"; #OR# print "@map[@val]\n"; } while( nextpermute(@val) ); } } return 0; }

Remove the #OR# bits to have the solution provided sorted in an order I like better.