Module 9: Supplemental Material


Tower of Hanoi

Let's build a GUI for the Tower of Hanoi:

Here's how we'll rewrite the main Tower-of-Hanoi solution: (source file)
import java.util.*;

public class TowerOfHanoi4 {

    // stacks[0], stacks[1] and stacks[2] are the three stacks.
    static Stack<Integer>[] towers;

    static HanoiGUI hanoiGUI;

    public static void main (String[] argv)
    {
        // A 4-disk puzzle:
        System.out.println ("4-Disk solution: ");
	solveHanoi (3, 0, 1);
    }


    static void solveHanoi (int n, int i, int j)
    {
        // Create the three stacks and initialize ... this code is the same ...

        // GUI. Note: n+1 = # disks. We will pass in the stacks.
        hanoiGUI = new HanoiGUI (towers, n+1);

        // Now solve recursively as before.
	solveHanoiRecursive (n, i, j);
    }
    

    static void solveHanoiRecursive (int n, int i, int j)
    {
        // ...
    }


    static void move (int n, int i, int j)
    {
        // Pull out the top disk on stack i and move to j ... same as before ...


        // This method will handle re-drawing the towers/disks.
        hanoiGUI.updateGUI ();

        // Pause execution for animation effect.
        try {
            Thread.sleep (1000);
        }
        catch (InterruptedException e) {
        }
    }


    static int other (int i, int j)
    {
       // ...
    }

}

Exercise 1: Download TowerOfHanoi4.java and the file HanoiGUI.class. Then compile and execute TowerOfHanoi4. You should see an animation of the solution. Next, download HanoiGUITemplate.java. Save the latter as HanoiGUI.java. Then compile and execute. You will notice that the GUI code in the template only draws the three towers. You are to fill in the code to draw the disks. All you need to do is call g.fillRect(), the parameters of which are: the topleft corner (first two parameters) and the width and height.


N-Queens

Let us examine the class ChessBoard: (source file)

The class ChessBoard has the code for displaying the board in a GUI. Let's examine some of this code:

Exercise 2: Download ChessBoard.java and NQueens.java. You will also need ImageTool.java and queen.jpg. Then, replace the char array in ChessBoard with an int equivalent. What changes do you need to make in the code? Would it be possible to use a boolean array?

An alternative data structure:

Exercise 3: Download ChessBoard2.java and NQueens2.java and read through the implementation of ChessBoard2. Apart from the space savings, what is the advantage of using the 1D array?


© 2006, Rahul Simha (revised 2017)