Java Reference
In-Depth Information
available for this purpose is exhausted. Your program shuts down and reports a
Ȓstack faultȓ.
Infinite recursion happens either because the parameter values don't get simpler or
because a special terminating case is missing. For example, suppose the getArea
method com putes the area of a triangle with width 0. If it wasn't for the special
test, the method would have constructed triangles with width ɨ1, ɨ2, ɨ3, and so on.
13.2 Permutations
We will now turn to a more complex example of recursion that would be difficult to
program with a simple loop. We will design a class that lists all permutations of a
string. A permutation is simply a rearrangement of the letters. For example, the string
ÐeatÑ has six permutations (including the original string itself):
"eat"
"eta"
"aet"
"ate"
"tea"
"tae"
As in the preceding section, we will define a class that is in charge of computing the
answer. In this case, the answer is not a single number but a collection of permuted
strings. Here is our class:
public class PermutationGenerator
{
public PermutationGenerator(String aWord) { È }
ArrayList<String> getPermutations() { È }
}
Here is the test program that prints out all permutations of the string "eat" :
ch13/permute/PermutationGeneratorDemo.java
1 import java.util.ArrayList;
2
3 /**
4 This program demonstrates the permutation generator.
5 */
Search WWH ::




Custom Search