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


in reply to How can I improve this?

Definitely TIMTOWTDI, but so far everyone agrees it's better (at least easier) to generate the permutations first and then sort the list, rather than trying to do both at once. Take a look at the Perl Cookbook section 4.15 (if you have it) for info on sorting lists based on a comparison function; it also has some effiency hints. I didn't do it by strings like the other Monks (which I realize differs from the form of your question), but this might be more efficient, and you can always regenerate the strings at the end. Here's what I came up:

#!/usr/bin/perl -w use strict; my (@a, @b, @c, @d, @e, $i1, $i2, $i3, $i4, $i5); @a = @b = @c = @d = @e = (0, 1, 2); # or whatever my (@unsorted, @sorted); for ($i1 = 0; $i1 <= $#a; $i1++) { for ($i2 = 0; $i2 <= $#b; $i2++) { for ($i3 = 0; $i3 <= $#c; $i3++) { for ($i4 = 0; $i4 <= $#d; $i4++) { for ($i5 = 0; $i5 <= $#e; $i5++) { push @unsorted, [$i1, $i2, $i3, $i4, $i5]; } } } } } @sorted = sort { non_zeros($b) <=> non_zeros($a) || ${$b}[0] <=> ${$a}[0] || ${$b}[1] <=> ${$a}[1] || ${$b}[2] <=> ${$a}[2] || ${$b}[3] <=> ${$a}[3] || ${$b}[4] <=> ${$a}[4] } @unsorted; print map "@$_\n", @sorted; sub non_zeros { my @arr = @{$_[0]}; scalar grep { $_ != 0 } @arr; }

I'm not a big fan of any of the permutation generators (including mine) listed so far; I'll try to think of something cleaner and more general.

Replies are listed 'Best First'.
RE: Re: How can I improve this?
by lhoward (Vicar) on Jul 25, 2000 at 07:51 UTC
    Since you seemed interested.. here is my permutation generator. It takes a base string (should be empty) as its first argument, then refrences to as many lists as you want as the other arguments and returns a refrence to a list containg all the list-element concatination permutations:
    my $foo=permute('',[0..2],[0..2],[0..3],[0..2]); sub permute{ my $prefix=shift; my @arrays=@_; my $c=shift @arrays; my @ret=(); foreach(@$c){ my $f=$prefix.$_; if(scalar(@arrays)==0){ push @ret,$f; }else{ my $t=permute($f,@arrays); push @ret,@$t; } } return \@ret; }
    I'm not really happy with the implementation of it, but I like it in spirit (of course, I'm a big fan of recursive algorithms to begin with).
      Well, since everyone is posting their permutors, here's mine:
      sub permute { my $last = pop @_; unless (@_) { return @$last; } return map { my $left = $_; map "$left$_", @$last } permute(@_); }

      -- Randal L. Schwartz, Perl hacker

      Drool
      by gryng (Hermit) on Jul 25, 2000 at 17:01 UTC
        Drool....

        Oh I like that.

        Mmmm,
        Gryn

        does this work? how do you call it?