Since
ago

Ferreira's Home Page


Perl camel, from http://dev.perl.org

Perl Bit #2: Make a Mess

Consider the problem: Given a list, rearrange its elements in any order. The problem can be rephrased as find a random permutation of the elements of the list.

A simple solution as a Perl subroutine is:

    sub permutation {
        my @array = @_;
        my @perm = ();
        while (@array) {
            my $idx = int rand(scalar @array);
            push @perm, $array[$idx];
            splice(@array, $idx, 1);
        }
        return @perm;
    }

You use that like this:

    my @list = qw(a b c d);
    my @perm = permutation(@list);
    print "(@perm)\n"
which produces outputs such as
    (a d b c)
    (a d c b)
    (b c a d)
Piece of case, isn't it?

KEYWORDS

permutation; random permutation; Perl 5