The permutations of the set is the set of sets:
The permutations of the set is the set of sets:
It's not easy to come up with a program to generate permutations. A good approach is recursion. Let's say you're trying to find all the permutations of . To use recursion, you'll make a recursive call to find all the permutations of a smaller set. Let's say a recursive call to generate all the permutations of correctly returns the set
How can we get all the permutations of the three animals?
Well, for each permutation of the two, you need to insert cat in each of its three possible positions:
From
dog mousethe three positions for insertion are:
^ dog ^ mouse ^This leads to the three permutations:
cat dog mouse dog cat mouse dog mouse cat
Similarly, from the other pair
mouse dogwe generate three more permutations from the three possible positions for inserting a cat:
cat mouse dog mouse cat dog mouse dog cat
The first step towards a permutation program then is to write a program to return the set obtained by inserting an item into the i'th position of a set v. We're going to use java.util.Vector for our sets.
Vector< E > insert(E item, int i, Vector< E > v) { Vector< E > newV = new Vector< E > (v); newV.add(i, item); return newV; }
Things to notice:
Of course, what we want is to to insert the item in all possible positions of the vector. So you'll need to return a set of sets. Look at the signature of insertAll() in Perms.java.
Considering we are working with sets of sets it's not as bad as it first appears! Honestly! All that's happening in insertAll() is that we are inserting the item into each possible position of the vector (as controled by the for loop), and adding the resulting vector to the growing set.
Finally we're ready for permute(). First notice its signature: It takes in a set and returns a set of sets. Does that make sense?
Then look at the base case. It's easy to permute a single element set. It's not quite a matter of doing nothing. To form all the permutations of the set you must return the set consisting of the only permutation of . So that's the base case of our recursion. Otherwise, we make a recursive call to get the set of permutations of rest (the result of removing the first element from v). And then, for each of the permutations of rest we need to insert the first element of v in all possible positions. Look at the code. Make sure you understand it. Because...
PermsInt.java is a program to test the permutation program with ints.
And finally, since Perms.java is generic, this next exercise will be a piece of cake.
java PermsString cat dog mouse cat dog mouse dog cat mouse dog mouse cat cat mouse dog mouse cat dog mouse dog cat