Generating permutations alone would constitute a good homework assignment, let alone the forced recursion and phone number distraction.
Small numbers of permutations can be generated efficiently through a method analogous to sorting networks. A sequence of n elements has n! permutations (assuming a full draw, with each permutation consisting of n elements as well). Observe that for a two-element sequence, there are two permutations:
- the original sequence, and
- the two elements swapped.
For a three-element sequence, there are six permutations:
- the permutations of the bottom two elements, then
- rotate the sequence one cell right (or left), and
- the permutations of the bottom two elements, then
- rotate the sequence one cell left (or right, opposite of above), and
- the permutations of the bottom two elements.
That is, it's the two-element version performed three times, with two intervening transformations. Now, a four-element sequence has twenty-four permutations:
- the permutations of the bottom three elements, then
- save position 1, assign 0 to 1, 3 to 0, and the saved value to 3, and
- the permutations of the bottom three elements, then
- swap positions 0 and 2, swap positions 1 and 3 (or rotate right by 2), and
- the permutations of the bottom three elements, then
- save position 3, assign 2 to 3, 0 to 2, and the saved value to 0, and
- the permutations of the bottom three elements.
Are you starting to see a pattern? Notice the recursive nature of the solution?
Above four elements, the patterns are harder to spot. You can iterate down the sequence, swapping the chosen element with the last element, reversing the sequence, expanding the bottom 24 permutations each time.
Try writing it out on paper, recording the steps you take to shuffle the elements, and you'll find you've written the program you need.
Note too that most of the solutions posted here use type String
and keep chopping it up and reassembling it. String
is a poor choice, given that it's immutable, when generating permutations is best done by swapping and rotating elements in a vector (really, a ring).
It's the rare case that you actually have to write the letters out to the destination stream, so bias your solution against that operation. Use an array of characters and write the characters to the stream one-by-one when it's time to emit a particular permutation. Forming a string just to dump the entry to a stream involves unnecessary allocation and copying.