01: /**
02:    This class generates permutations of a word.
03: */
04: class PermutationGenerator
05: {
06:    /**
07:       Constructs a permutation generator.
08:       @param aWord the word to permute
09:    */
10:    public PermutationGenerator(String aWord)
11:    {
12:       word = aWord;
13:       current = 0;
14:       if (word.length() > 1)
15:          tailGenerator = new PermutationGenerator(word.substring(1));
16:       System.out.println("Generating " + word );
17:    }
18: 
19:    /**
20:       Computes the next permutation of the word.
21:       @return the next permutation
22:    */
23:    public String nextPermutation()
24:    {
25:       if (word.length() == 1)
26:       {
27:          current++;
28:          return word;
29:       }
30: 
31:       String r = word.charAt(current) + tailGenerator.nextPermutation();
32: 
33:       if (!tailGenerator.hasMorePermutations())
34:       {
35:          current++;
36:          if (current < word.length())
37:          {
38:             String tailString = word.substring(0, current)
39:                + word.substring(current + 1);
40:             tailGenerator = new PermutationGenerator(tailString);
41:          }
42:       }
43: 
44:       return r;
45:    }
46: 
47:    /**
48:       Tests whether there are more permutations.
49:       @return true if more permutations are available
50:    */
51:    public boolean hasMorePermutations()
52:    {
53:       return current < word.length();
54:    }
55: 
56:    private String word;
57:    private int current;
58:    private PermutationGenerator tailGenerator;
59: }