Towers of Hanoi Code
By: Steve • Research Paper • 3,073 Words • February 7, 2010 • 1,118 Views
Join now to read essay Towers of Hanoi Code
/*
This applet solves the Towers of Hanoi problem for a tower of 10 disks.
(Ten differntly-sized disks are stacked in a pile, in order of
decreasing size. There are two other places for piles. The object
is to move the pile to the second available place, subject to the
rules that only one disk at a time can be moved, and no disk can
be piled on top of a smaller disk.) The solution is shown as
an animation. The Towers of Hanoi problem is a standard example
of recursion.
The solution is repeated over and over indefinitely.
The applet MUST have a width of 430 and a height of 143.
*/
import java.awt.*;
import java.applet.Applet;
public class TowersOfHanoi extends Applet implements Runnable {
private static Color BACKGROUND_COLOR = new Color(255,255,180);
private static Color BORDER_COLOR = new Color(100,0,0);
private static Color DISK_COLOR = new Color(0,0,180);
private static Color MOVE_DISK_COLOR = new Color(180,180,255);
private Image OSC; // The off-screen canvas.
private static final int GO = 1, SUSPEND = 2, TERMINATE = 3; // Values for status.
private int status = GO; // Controls the execution of the thread.
private Thread runner; // A thread to run the animation.
/* The following variables are the data needed for the animation. The
three "piles" of disks are represented by the variables tower and
towerHeight. towerHeight[i] is the number of disks on pile number i.
For i=0,1,2 and for j=0,1,...,towerHeight[i]-1, tower[i][j] is an integer
representing one of the ten disks. (The disks are numbered from 1 to 10.)
(tower is null between repetitions of the solution.)
During the solution, as one disk is moved from one pile to another,
the variable moveDisk is the number of the disk that is being moved,
and moveTower is the number of the pile that it is currently on.
This disk is not stored in the tower variable. it is drawn in a
different color from the other disks.
All the data in these variables is for use in the drawCurrentFrame() method,
which redraws the whose picture for each frame of the animation.
*/
private int[][] tower;
private int[] towerHeight;
private int moveDisk;
private int moveTower;
public void init() {
// Initialize the applet by setting the background color.
setBackground(BACKGROUND_COLOR);
}
public void run() {
// Run the animated solution over and over until the status
// variable is set to TERMINATED. When this happens, the
// delay() method will throw an IllegalArgumentException