Java Reference
In-Depth Information
}
public boolean hasMorePermutations()
{
if (a.length <= 1) return false;
for (int i = a.length - 1; i > 0; i--)
{
if (a[i - 1] < a[i]) return true;
}
return false;
}
public void swap(int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public void reverse(int i, int j)
{
while (i < j) { swap(i, j); i++; j--; }
}
private int[] a;
}
621
622
The algorithm uses the fact that the set to be permuted consists of
distinct numbers. Thus, you cannot use the same algorithm to compute
the permutations of the characters in a string. You can, however, use this
class to get all permutations of the character positions and then compute
a string whose i th character is word.charAt(a[i]) . Use this
approach to reimplement the PermutationIterator of Exercise
P13.11 without recursion.
΢΢ Exercise P13.13. Towers of Hanoi. This is a well-known puzzle. A stack
of disks of decreasing size is to be transported from the leftmost peg to the
rightmost peg. The middle peg can be used as temporary storage (see
Figure 5 ). One disk can be moved at one time, from any peg to any other
peg. You can place smaller disks only on top of larger ones, not the other
way around.
Write a program that prints the moves necessary to solve the puzzle for n
disks. (Ask the user for n at the beginning of the program.) Print moves in
the form
Search WWH ::




Custom Search