Okay so I have an assignment on the tower of Hanoi problem. I got the code and got it working but I just don't know what's going on behind it. Can someone please explain? I don't understand the lines where it says solveTower(num-1, from, other, to)
and solveTower(1, from, to, other)
and solveTower(num-1, other, to, from)
. I understand what it is doing, it's just moving the number of disks from one peg to another using the other one. I just don't understand what's going on behind it. Like why do I have to move the num-1
disks from the left peg to the middle, the move the biggest disk from the left peg to right peg, and move the num-1
disks from the middle to the right? Why can't I just say something like solveTower(num, from, to, other)
to move all the disks from the left peg to the right peg?
Here's my driver:
public class Hanoi_Driver
{
public static void main(String[] args)
{
Tower tower = new Tower();
tower.solveTower();
}
}
And here's my object:
import java.util.Scanner;
public class Tower
{
private int size;
private String fromPeg = "A";
private String toPeg = "C";
private String otherPeg = "B";
public Tower()
{
this.size = size;
this.fromPeg = fromPeg;
this.toPeg = toPeg;
this.otherPeg = otherPeg;
}
public void solveTower()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("What do you want the size to be?");
size = keyboard.nextInt();
System.out.println("Steps for solving " + size + " disk tower of hanoi puzzle, ");
solveTower(size, fromPeg, toPeg, otherPeg);
}
private void solveTower(int num, String from, String to, String other) {
if (num == 1) {
System.out.println("Move disk from " + from +
" to " + to + ".");
}
else {
solveTower(num-1, from, other, to);
solveTower(1, from, to, other);
solveTower(num-1, other, to, from);
}
}
}