Question: This is a Java related problem, from the book Introduction to Programming in Java by Sedgewick. Here is the problem: Consider the following variant of
This is a Java related problem, from the book Introduction to Programming in Java by Sedgewick.
Here is the problem:
Consider the following variant of the towers of Hanoi problem. There * are 2n discs of increasing size stored on three poles. Initially all * of the discs with odd size (1, 3, ..., 2n-1) are piled on the left * pole from top to bottom in increasing order of size; all of the discs * with even size (2, 4, ..., 2n) are piled on the right pole. Write a * program to provide instructions for moving the odd discs to the right * pole and the even discs to the left pole, obeying the same rules as * for towers of Hanoi.
Here's the baseline recursive function for Towers of Hanoi:
public static void moves(int n, boolean left) {
if (n == 0)
return;
moves(n - 1, !left);
if (left) {
System.out.println(n + " move to left");
}
else {
System.out.println(n + " move to right");
}
moves(n - 1, !left);
}
public static void main(String[] args) {
System.out.print("Enter Number of Discs: ");
int n = Integer.parseInt(args[0]);
moves(n, true);
}
}
How would you modify this program to accomplish the above scenario? Please pay special attention to the instructions pertaining to even and odd disks.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
