Recursively implement a java solution to towers of hanoi


Recursively implement a java solution to towers of hanoi problem so that the stepwise states of the towers are included the output must be as follows

Initially:
peg0: 3 2 1
peg1: 0 0 0
peg2: 0 0 0

Step 1: Move disk1 from peg0 to peg2 resulting
peg0: 3 2 0
peg1: 0 0 0
peg2: 1 0 0

Step 2: Move disk2 from peg0 to peg1 resulting
peg0: 3 0 0
peg1: 2 0 0
peg2: 1 0 0

In order to get the output I have to modify this java program


public class TowersofHanoi {

private int totalDisks;

public TowersofHanoi (int disks)
{
totalDisks = disks;

}

public void solve ()
{
moveTower (totalDisks,0,2,1);
}

private void moveTower (int numDisks, int start, int end, int temp)
{
if (numDisks ==1)
moveOneDisk (start, end);
else
{
moveTower (numDisks-1, start, temp, end);
moveOneDisk (start, end);
moveTower (numDisks-1, temp, end, start);
}
}

private void moveOneDisk (int start, int end)
{
System.out.println("Move one disk from " + start + " to " + end);
}


}

 

public class SolveTowers {

public static void main(String[] args) {

TowersofHanoi towers = new TowersofHanoi (3);

towers.solve();

}

}

Solution Preview :

Prepared by a verified Expert
JAVA Programming: Recursively implement a java solution to towers of hanoi
Reference No:- TGS02361020

Now Priced at $10 (50% Discount)

Recommended (98%)

Rated (4.3/5)