Source of Hanoi.java


  1: //Hanoi.java
  2: //Describes the movement of discs to solve the Towers of Hanoi problem.

  4: import java.util.Scanner;

  6: public class Hanoi
  7: {
  8:     public static void main(String[] args)
  9:     {
 10:         System.out.println
 11:         (
 12:             "\nThis program solves the Tower of Hanoi "
 13:             + "problem by describing the sequence\nof disc moves that "
 14:             + "will achieve the transfer of n discs from the initial"
 15:             + "\npost to the final post, according to the following rules:"
 16:             + "\n\n"
 17:             + "1. Only one disc can be moved at a time.\n"
 18:             + "2. No disc can be placed on top of a smaller disc."
 19:             + "\n\n"
 20:             + "The amount of time to compute the moves increases "
 21:             + "dramatically as the\nnumber of discs increases. For "
 22:             + "illustrative purposes keep the number\nof discs to "
 23:             + "four or five at most.\n"
 24:         );

 26:         Scanner keyboard = new Scanner(System.in);
 27:         int n;
 28:         System.out.print("Enter the number of discs to move: ");
 29:         n = keyboard.nextInt();
 30:         describeDiscMoves(n, 1, 3);
 31:         System.out.println();
 32:     }

 34:     public static void describeDiscMoves
 35:     (
 36:         int n,
 37:         int startPost,
 38:         int endPost
 39:     )
 40:     /**
 41:         Display the order in which disks must be moved and to which
 42:         posts in order to move n disks from startPost to endPost.
 43:         @param n The number of disks to be moved.
 44:         @param startPost The post holding all disks at the start.
 45:         @param endPost The post to which all disks must be moved.
 46:         <p>Pre:<p>n, startPost and endPost have been initialized.
 47:         <p>Post:<p>All moves necessary for moving n disks from
 48:         startPost to endPost have been displayed.
 49:     */
 50:     {
 51:         int tempPost;
 52:         if (n == 1)
 53:             System.out.println
 54:             (
 55:                 "Move the top disc from post "
 56:                 + startPost + " to post " + endPost + "."
 57:             );
 58:         else
 59:         {
 60:             tempPost = 6 - startPost - endPost;
 61:             describeDiscMoves(n - 1, startPost, tempPost);
 62:             System.out.println
 63:             (
 64:                 "Move the top disc from post "
 65:                 + startPost + " to post " + endPost + "."
 66:             );
 67:             describeDiscMoves(n - 1, tempPost, endPost);
 68:         }
 69:     }
 70: }