Exemple #1
0
  private static void drawDisks(ArrayList[] pegList) {
    int peg, j, k;
    RectShape rect = null;

    // erase the previous drawing and set the line and labels
    DrawTools.eraseWindow();
    line.draw();
    pTextA.draw();
    pTextB.draw();
    pTextC.draw();

    // scan pegList to identify the disks on each peg; use the
    // disk value set rectangle attributs using constants from
    // arraysxPos, diskWidth, and color;  then draw the
    // disk (rectangle)
    for (peg = 0; peg <= 2; peg++)
      for (j = 0; j < pegList[peg].size(); j++) {
        k = ((Integer) (pegList[peg]).get(j)).intValue();

        rect = new RectShape(xPos[peg * 6 + k], 4 - (j * 0.5), diskWidth[k], 0.5, color[k]);
        rect.draw();
      }
    // delay the frame 1 second
    DrawTools.delayWindow(1.0);
  }
Exemple #2
0
  public static void main(String[] args) {
    // number of disks
    int n = 0, i;

    // enter the number of disks on the command line.
    // convert args[0] to n
    try {
      n = Integer.parseInt(args[0]);
    } catch (ArrayIndexOutOfBoundsException aiobe) {
      System.err.println("***\n  Enter the number of disks " + "on the command line\n***");
      System.exit(1);
    }

    // declare a three element array for the three needles.
    // each element is an ArrayList of integers that holds
    // the stack of disks for each needle
    ArrayList[] needleList = new ArrayList[3];

    for (i = 0; i < needleList.length; i++) needleList[i] = new ArrayList();

    // initialize needle = 0 to hold the n disks 0, 1, ..., n-1
    for (i = 0; i < n; i++) needleList[0].add(i);

    // open the drawing surface and display initial disks
    DrawTools.openWindow();
    drawDisks(needleList);
    // call recursive function
    hanoi(n, 0, 1, 2, needleList);

    // view final display and close the drawing surface
    DrawTools.viewWindow();
    DrawTools.closeWindow();
  }