Question: Change the permutations method of Section 13.4 (which computed all permutations at once) to a PermutationIterator (which computes them one at a time). Now we

Change the permutations method of Section 13.4 (which computed all permutations at once) to a PermutationIterator (which computes them one at a time).

public class Permutation Iterator { public Permutation Iterator (String s) { .

Now we need a way to iterate through the permutations recursively. Consider the string "eat". As before, we’ll generate all permutations that start with the letter 'e', then those that start with 'a', and finally those that start with 't'. How do we generate the permutations that start with 'e'? Make another PermutationIterator object (called tailIterator) that iterates through the permutations of the substring "at". In the nextPermutation method, simply ask tailIterator what its next permutation is, and then add the 'e' at the front. However, there is one special case. When the tail generator runs out of permutations, all permutations that start with the current letter have been enumerated. Then • Increment the current position.
• Compute the tail string that contains all letters except for the current one.
• Make a new permutation iterator for the tail string.
You are done when the current position has reached the end of the string.

public class Permutation Iterator { public Permutation Iterator (String s) { . public String next Permutation () {...} public boolean hasMorePermutations () {...} } } Here is how you would print out all permutations of the string "eat": PermutationIterator iter = new PermutationIterator ("eat"); while (iter.hasMore Permutations()) { System.out.println (iter.nextPermutation ()); }

Step by Step Solution

3.46 Rating (153 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

To create an iterator that generates permutations one at a time we can implement the PermutationIterator class in Java Each instance of PermutationIte... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Java Programming Questions!