Perl: Array element permutation

cburwell

Limp Gawd
Joined
Apr 2, 2005
Messages
269
I am having some trouble wrapping my head around this problem.

I have an array with five words in it. Each word is it's own element, like so:

@words = ("word0", "word1", "word2", "word3", "word4");

What I want to do is print out all permutations of these five words. If I did the math right, there is about 120 different permuatitions of these words.

I thought I would be able to print them with a loop, but I cannot seem to figure out how to do this.

Cn anyone offer any help?
 
Section 4.20 of Perl Cookbook by Christiansen and Torkington, 2nd edition, shows a couple of implementations.

If you don't have the book, I think you can find a general permutation algorithm pretty easily by searching the web.
 
In general a permutation algorithm can be devised by starting with a good base case (what are the permutations of a 1-element set) and then building on that. Most beginning permutation algorithms will probably take a recursive approach although it is not strictly necessary but may be easier.
 
Back
Top