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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.