Source of PermutationsSolution.java


  1: //PermutationsSolution.java

  3: import java.util.Scanner;

  5: public class PermutationsSolution
  6: {
  7:     static int permutationCount = 0;

  9:     public static void permuteString
 10:     (
 11:         String head,
 12:         String tail
 13:     )
 14:     {
 15:         char current;
 16:         String newPermute;
 17:         int len;
 18:         int i;

 20:         current = '?';
 21:         len = tail.length();

 23:         if (len <= 1)
 24:         {
 25:             ++permutationCount;
 26:             System.out.println(permutationCount + ") " + head + tail);
 27:         }
 28:         else
 29:         {
 30:             for (i = len - 1; i >= 0; --i)
 31:             {
 32:                 current = tail.charAt(i); // Get next leading character
 33:                 newPermute = tail.substring(0, i) + tail.substring(i + 1);
 34:                 // Get the rest of the tail
 35:                 permuteString(head + current, newPermute);
 36:             }
 37:         }
 38:     }

 40:     public static void main(String [] args)
 41:     {
 42:         final String PROMPT_STRING =
 43:             "Enter a string to permute in reverse (<Enter> to exit): ";
 44:         Scanner scnr = new Scanner(System.in);
 45:         String input;

 47:         // Get input and permute the string
 48:         System.out.println(PROMPT_STRING);
 49:         input = scnr.nextLine();

 51:         while (input.length() > 0)
 52:         {
 53:             permutationCount = 0;
 54:             permuteString("", input);
 55:             System.out.println(PROMPT_STRING);
 56:             input = scnr.nextLine();
 57:         }
 58:         System.out.println("Done.");
 59:     }
 60: }