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)
    {
       // ...
    }

}


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:

An alternative data structure: