Fellow monks,

Following my attempts to write elegant "Lispy" code in Perl I came upon the interesting algorithm of recursive generation of permutations. I.e. for (1 2 3) the permutations are (1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1).

Like many problems, though at first seemingly difficult, recursion is a powerful technique for extremely elegant solutions.

All permutations of N elements can be expressed in terms of all permutations of N - 1 elements. Having a set of N elements, we take one of them and append it to all the permutations of the remaining N - 1 elements. Repeating it for every element of N gives us all permutations of N elements. Unsurprisingly, it fits well into the known formula of the amount of permutations of N elements: the factorial of N, N!.

This is expressed very succinctly and elegantly by the following Lisp code (8 lines without comments / documentation):

(defun permutations (bag) "Return a list of all the permutations of the input." ;; If the input is nil, there is only one permutation: ;; nil itself (if (null bag) '(()) ;; Otherwise, take an element, e, out of the bag. ;; Generate all permutations of the remaining elements, ;; And add e to the front of each of these. ;; Do this for all possible e to generate all permutations. (mapcan #'(lambda (e) (mapcar #'(lambda (p) (cons e p)) (permutations (remove e bag :count 1)))) bag)))

Lisp's command of lists shines in this example, and replicating the code in Perl as succinctly (without sacrificing readability) is quite challenging. What I paste below is a straightforward implementation, without delving too much into succinctness.

First, lets define a couple of helper functions:

sub is_empty_list { return @{$_[0]} == 0; } # remove ($what, $list, $howmany) # # Removes $what from the list $list up to $howmany times. # If $howmany is not provided, removes all occurrences of $what. # sub remove { my $what = $_[0]; my $list = $_[1]; my $howmany = defined $_[2] ? $_[2] : -1; my @ret = (); foreach my $elem (@{$list}) { push @ret, $elem unless ($elem == $what and $howmany-- > 0); } return \@ret; }
remove would look good if it were not for the argument collection. Named arguments with support for optional arguments that have default values would be of great help. Happily, it will be provided in Perl6, and this function will look much better.

Now, to the permutations function itself:

sub permutations { my $bag = $_[0]; if (is_empty_list($bag)) { return [[]]; } my $perms = []; foreach my $elem (@$bag) { foreach my $perm (@{permutations(remove($elem, $bag, 1))}) { unshift(@{$perm}, $elem); push(@{$perms}, $perm); } } return $perms; }
This could have been made much nicer if Perl had a sane way to write nested maps... Also, it seems to me that unshift and push would be much better understood as prepend and append.

Any ideas/suggestion to make this code more elegant ?


In reply to recursively generating permutations by spurperl

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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, details, 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, summary, 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.