Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- The constructor accepts one argument, a char[] of the characters to be permuted.
- A boolean method named hasNext() that returns true if there is at least one more permutation or false if all permutations have been generated.
- A method named next() that returns a char[] of the next permutation.
- Use the following main program, as part of the Permute class, to test your permutation generator.
- public static void main(String[] args) {
- char[] symbols = { 'A', 'D', 'E', 'P', 'T' };
- Permute permutationGenerator = new Permute(symbols);
- int count = 0;
- while (permutationGenerator.hasNext()) {
- count++;
- symbols = permutationGenerator.next();
- for (char ch : symbols) System.out.print(" " + ch);
- System.out.println();
- }
- System.out.println("Total number of permutations = " + count);
- }
- Advice
- One idea for generating permutations of N distinct values is to generalize the approach described in the following example that generates the permutations for the three symbols A, B, and C.
- Step Description Resulting List
- 1 Start with the original list. ABC (1'st permutation)
- 2 General idea is to move the first symbol ('A') progressively to its right.
- 2a Swap 'A' with its neighbour to the right. BAC (2'nd permutation)
- 2b Swap 'A' with its neighbour to the right. BCA (3'rd permutation)
- 3 When a symbol reaches the rightmost position, return it to its original position.
- 3a 'A' has no neighbour to its right. It returns to its original position. This is not a new permutation (because the swap failed). ABC (No Output)
- 3b Swap the original second symbol('B') with its neighbour to the right. ACB (4'th permutation)
- 4 Move the first symbol progressively to its right (a repeat of step 2).
- 4a Swap 'A' with its neighbour to the right. CAB (5'th permutation)
- 4b Swap 'A' with its neighbour to the right. CBA (6'th permutation)
- 5 When a symbol reaches the rightmost position, return it to its original position (a repeat of step 3).
- 5a 'A' has no neighbour to its right. It returns to its original position. This is not a new permutation (because the swap failed). ACB (No Output)
- 5b 'B' has no neighbour to its right. It returns to its original position. This is not a new permutation (because the swap failed). ABC (No Output)
- 5c 'C' has no neighbour to its right. It returns to its original position. This is not a new permutation (because the swap failed). ABC (No Output)
- 5d There is no fourth symbol. The algorithm stops. ABC (No Output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement