13.2 M o r e Examples with Simple Variables | 647
public static voiddoTowers(
int circleCount, // Number of circles to move
int beginPeg, // Peg containing circles to move
int auxPeg, // Peg holding circles temporarily
int endPeg ) // Peg receiving circles being moved
// Moves are written on file outFile.
// This recursive method moves circleCount circles from beginPeg
// to endPeg. All but one of the circles are moved from beginPeg
// to auxPeg, then the last circle is moved from beginPeg to
// endPeg, and then the circles are moved from auxPeg to endPeg.
// The subgoals of moving circles to and from auxPeg involve recursion.
{
outFile.println("#circles: "+ circleCount + " Begin: "+
beginPeg + " Auxil: "+ auxPeg + " End: "+ endPeg);
if (circleCount > 0)
{
// Move n – 1 circles from beginning peg to auxiliary peg
outFile.print("From first: ");
doTowers(circleCount-1, beginPeg, endPeg, auxPeg);
outFile.println("Move circle "+ circleCount + " from peg "
+ beginPeg + " to peg "+ endPeg);
// Move n – 1 circles from auxiliary peg to ending peg
outFile.print("From second: ");
doTowers(circleCount – 1, auxPeg, beginPeg, endPeg);
}
}
}
The output from a run with three circles follows. “Original” means that the parameters
listed beside it are from the nonrecursive call, which is the first call to doTowers. “From first”
means that the parameters listed are for a call issued from the first recursive statement. “From
second” means that the parameters listed are for a call issued from the second recursive state-
ment. Notice that a call cannot be issued from the second recursive statement until the pre-
ceding call from the first recursive statement has completed its execution.