// Exercise. 4.38: TowersOfHanoi.java
// Recursive approach
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;

public class TowersOfHanoi extends Applet
implements ActionListener {
    Label QuantityOfDisksLabel;
    TextField QuantityOfDisksInput;
    long CallDepth;
    long Steps;
    int DisksOnPeg[] = new int [ 4 ];//there are 3 pegs we want to refer to 1 -> 3
    public void init()
    {// set up the GUI
        //First create the prompt, i.e. invoke the constructor for the Label object
        QuantityOfDisksLabel = new Label( "Towers of Hanoi. Enter a positive nonzero integer for the number of disks and press return" );
        //Now invoke the constructor for the object to hold the input
        QuantityOfDisksInput = new TextField( 10 );
        QuantityOfDisksInput.addActionListener( this );
        //put our objects on the Applet's Window
        add( QuantityOfDisksLabel );
        add( QuantityOfDisksInput);

    }

    public void actionPerformed( ActionEvent e )
    {
        final int InitialPeg=1, DestinationPeg=3, HoldingPeg=2;
        int QuantityOfDisks;

        CallDepth = 0;
        Steps = 0;

        QuantityOfDisks = Integer.parseInt( QuantityOfDisksInput.getText() );
        DisksOnPeg [ 1 ] = QuantityOfDisks;
        showStatus("Call depth =" + CallDepth + "Calculating ..." );
        tower(QuantityOfDisks, 	InitialPeg, DestinationPeg, HoldingPeg);
        showStatus( "Done." );

    }

    // Recursive definition of method tower
    void tower(int DiskCount, int StartPeg, int EndPeg, int HoldPeg )
    {
        CallDepth++;
        showStatus("Call depth =" + CallDepth + "Calculating ..." );
        if(DiskCount == 1){
            Steps++;
            System.out.println( StartPeg + " -> " + EndPeg);
            DisksOnPeg [ StartPeg ]--;
            DisksOnPeg [ EndPeg ]++;
	} //end if

            else{ //recursive case
                tower(DiskCount -1, StartPeg, HoldPeg, EndPeg);
                Steps++;
                DisksOnPeg [ StartPeg ]--;
                DisksOnPeg [ EndPeg ]++;

                System.out.println( StartPeg + " -> " + EndPeg);
                tower(DiskCount -1, HoldPeg, EndPeg, StartPeg);
            } //end else
            CallDepth--;
    }//end method tower
}//end class TowersOfHanoi
