Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.45 KB | None | 0 0
  1. The constructor accepts one argument, a char[] of the characters to be permuted.
  2. A boolean method named hasNext() that returns true if there is at least one more permutation or false if all permutations have been generated.
  3. A method named next() that returns a char[] of the next permutation.
  4. Use the following main program, as part of the Permute class, to test your permutation generator.
  5.  
  6.  
  7. public static void main(String[] args) {
  8.   char[] symbols = { 'A', 'D', 'E', 'P', 'T' };
  9.   Permute permutationGenerator = new Permute(symbols);
  10.   int count = 0;
  11.   while (permutationGenerator.hasNext()) {
  12.     count++;
  13.     symbols = permutationGenerator.next();
  14.     for (char ch : symbols) System.out.print(" " + ch);
  15.     System.out.println();
  16.   }
  17.   System.out.println("Total number of permutations = " + count);
  18. }
  19.  
  20. Advice
  21. 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.
  22.  
  23. Step    Description Resulting List
  24. 1  Start with the original list.    ABC (1'st permutation)
  25. 2  General idea is to move the first symbol ('A') progressively to its right.
  26. 2a  Swap 'A' with its neighbour to the right.   BAC (2'nd permutation)
  27. 2b  Swap 'A' with its neighbour to the right.   BCA (3'rd permutation)
  28. 3  When a symbol reaches the rightmost position, return it to its original position.
  29. 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)
  30. 3b  Swap the original second symbol('B') with its neighbour to the right.   ACB (4'th permutation)
  31. 4  Move the first symbol progressively to its right (a repeat of step 2).
  32. 4a  Swap 'A' with its neighbour to the right.   CAB (5'th permutation)
  33. 4b  Swap 'A' with its neighbour to the right.   CBA (6'th permutation)
  34. 5  When a symbol reaches the rightmost position, return it to its original position (a repeat of step 3).
  35. 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)
  36. 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)
  37. 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)
  38. 5d  There is no fourth symbol.  The algorithm stops.    ABC (No Output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement