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) nonunique 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= $last1; # Find last item not in reversesorted
+ 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.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
 a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)

For: 

Use: 
 &   & 
 <   < 
 >   > 
 [   [ 
 ]   ] 
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.

