Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Towers of Hanoi Step-Through Recursive

RyanFRyanF Posts: 1Member
The way my book words this problem is confusing me greatly. I have been sitting here trying to understand what it means by certain things for hours. I also know the conventional recursive solution to the Towers of Hanoi and was wondering if anyone had some insight as to how to solve this version of the problem.

[quote]
Write a program the prints the moves necessary to solve the puzzle for n disks.

Implement a class DiskMover. The constructor takes:
1. The source peg from which to move the disks(1, 2, or 3)
2. The target peg to which to move the disks(1, 2, or 3)
3. The number of discs to move.

A disk mover that moves a single disk from one peg to another simply has a nextMove method that returns a string.
"Move disk from peg source to peg target."

A disk mover with more than one disk to move must work harder. It needs another DiskMover to help it. In the constructor, construct a DiskMover(source, other, disks -1) where other is the peg other than from and target.

The nextMove asks that disk mover for its next move until it is done. The effect is to move the first disks - 1 to the other peg. Then the nextMove method issues a command to move a disk from the from peg to the to peg. Finally, it constructs another disk mover DiskMover(other, target, disks -1) that generates the moves that move the disks from the other peg to the target peg.

Test your program as follows:
[code]
DiskMover mover = new DiskMover(1, 3, n);
while(mover.hasMoreMoves())
{
System.out.println(mover.nextMove());
}
[/code]
[/quote]

Iv'e been working on this for 5 hours and can never seem to get past this stage in the code:
[code]public class DiskMover {

int source, target, other, n;
String move;

public DiskMover(int from, int to, int disks) {
source = from;
target = to;
n = disks;
other = 6 - source - target;

if (n == 0) {
return;
}

new DiskMover(source, other, n - 1);
move = "Move disk from peg " + source + " to peg " + target;

}

public String nextMove() {

if (n > 1) {
new DiskMover(other, target, n - 1);
}

return move;

}

public boolean hasMoreMoves() {

}

}
[/code]

Any kind of advice on how to get started or anything would be greatly appreciated.


Sign In or Register to comment.