Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: How can I improve this?

by tye (Cardinal)
on Jul 26, 2000 at 02:21 UTC ( #24364=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: How can I improve this?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://24364]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (6)
As of 2014-11-01 01:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (227 votes), past polls