Thursday, October 7, 2010

Assignment #11 CS360

Assignment #11
"Towers of Hanoi & Towers of Hanoi Test"
10-07-10





/*
Towers of Hanoi
*/


public class TowersOfHanoi
{
private int numDisks; //number of disks to move

public TowersOfHanoi( int disks )
{
numDisks = disks;
}

//recursively more disks between towers
public void solveTowers( int disks, int sourcePeg, int destinationPeg, int tempPeg)
{
//base case -- only one disk to move
if( disks == 1)
{
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg);
return;
}

//recursion step -- move (disk 1) disks from sourcePeg
//to tempPeg using destinationPeg
solveTowers( disks - 1, sourcePeg, tempPeg, destinationPeg );

//move last disk from sourcePeg to destinationPeg
System.out.printf( "\n%d --> %d", sourcePeg, destinationPeg );

//move (disks - 1) disks from tempPeg to destinationPeg
solveTowers( disks - 1, tempPeg, destinationPeg, sourcePeg );
}
}




~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|~|



/*
main function to be run
*/

public class TowersOfHanoiTest
{
public static void main( String args[])
{
int startPeg = 1; //value 1 used to indicate startPeg in output
int endPeg = 3; //value 3 used to indicate endPeg in output
int tempPeg = 2; //value 2 used to indicate tempPeg output
int totalDisks = 3; //number of disks
TowersOfHanoi towersOfHanoi = new TowersOfHanoi( totalDisks );

//initial nonrecursive call: move all disks
towersOfHanoi.solveTowers( totalDisks, startPeg, endPeg, tempPeg );
}
}

No comments:

Post a Comment