
Educators: Earn a free Gold upgrade by joining the PBwiki Back To School Challenge.

Questions? Join PBwiki's weekly office hours today at 1 PM Eastern and get live answers.
PART2:
Write a program that will solve the problem for 4 disks and 3 pegs.
//********************************************************************
// TowersOfHanoi.java
//
// Represents the classic Towers of Hanoi puzzle.
//
// This code was base in the example of Lewis and chase in their
// book: "Java Software Structures"
//
//********************************************************************
public class TowersOfHanoi {
private int totalDisks; // total disks playing in the towers
public TowersOfHanoi ( ) {
this.totalDisks = 0;
}
//-----------------------------------------------------------------
// Sets up the puzzle with the specified number of disks.
//-----------------------------------------------------------------
public TowersOfHanoi ( int disks ) {
this.totalDisks = disks ;
this.solve ( ) ;
}
// MUTATOR:
public void setTotalDisks ( int totalDisks ) {
this.totalDisks = ( 0 <= totalDisks ) ? totalDisks : 0 ;
}
//ACCESSOR:
public int getTotalDisks ( ) {
return this.totalDisks ;
}
//-----------------------------------------------------------------
// Performs the initial call to moveTower to solve the puzzle.
// Moves the disks from tower 1 to tower 3 using tower 2.
//-----------------------------------------------------------------
public void solve ( ) {
this.moveTower ( this.getTotalDisks ( ) , 1 , 3 , 2 ) ;
}
//-----------------------------------------------------------------
// Moves the specified number of disks from one tower to another
// by moving a subtower of n-1 disks out of the way, moving one
// disk, then moving the subtower back. Base case of 1 disk.
//-----------------------------------------------------------------
private void moveTower ( int numDisks, int start, int end, int temp ) {
if ( 1 == numDisks ) {
this.moveOneDisk ( start , end ) ;
}
else {
this.moveTower ( numDisks-1, start , temp , end ) ;
this.moveOneDisk ( start , end ) ;
this.moveTower (numDisks-1, temp, end, start);
}
}
//-----------------------------------------------------------------
// Prints instructions to move one disk from the specified start
// tower to the specified end tower.
//-----------------------------------------------------------------
private void moveOneDisk ( int start , int end ) {
System.out.println ( "Move one disk from " + start + " to " + end ) ;
}
public static void main ( String args [ ] ) {
TowersOfHanoi hanoi = new TowersOfHanoi ( 4 );
}
}
Page Information
|
Wiki Information |
Recent PBwiki Blog Posts |