Advertisement
calcpage

LACS07a_AnimatedHanoi.java

Jun 12th, 2012
308
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 2.23 KB | None | 0 0
  1. /*************************************************************************
  2.  *  Compilation:  javac AnimatedHanoi.java
  3.  *  Execution:    java AnimatedHanoi N
  4.  *  Dependencies: StdDraw.java
  5.  *  
  6.  *  Solves the Towers of Hanoi problem on N discs and displays the
  7.  *  results graphically.
  8.  *
  9.  *
  10.  *  % java AnimatedHanoi 6
  11.  *
  12.  *************************************************************************/
  13.  
  14. import java.awt.Color;
  15.  
  16. public class AnimatedHanoi {
  17.  
  18.    // draw the current state of the Towers of Hanoi game
  19.    public static void draw(int[] pole) {
  20.  
  21.       int N = pole.length - 1;
  22.  
  23.       // draw 3 poles
  24.       StdDraw.clear();
  25.       StdDraw.setPenColor(StdDraw.BLACK);
  26.       StdDraw.setPenRadius(0.002);
  27.       for (int i = 0; i < 3; i++)
  28.          StdDraw.line(i, 0, i, N);
  29.  
  30.       // draw N discs
  31.       int[] discs = new int[3];   // discs[p] = # discs on pole p
  32.       for (int i = N; i >= 1; i--) {
  33.          Color color = Color.getHSBColor(1.0f * i / N, .7f, .7f);
  34.          StdDraw.setPenColor(color);
  35.          StdDraw.setPenRadius(0.035);   // magic constant
  36.          double size = 0.5 * i / N;
  37.          int p = pole[i];
  38.          StdDraw.line(p-size/2, discs[p], p + size/2, discs[p]);
  39.          ++discs[p];
  40.       }
  41.  
  42.       StdDraw.show(500);
  43.    }
  44.  
  45.    public static void hanoi(int N) {
  46.       int[] pole = new int[N+1];       // pole[i] = pole (0-2) that disc i is on
  47.       draw(pole);
  48.       hanoi(N, 0, 1, 2, pole);
  49.    }
  50.  
  51.    public static void hanoi(int n, int from, int temp, int to, int[] pole) {
  52.       if (n == 0) return;
  53.       hanoi(n-1, from, to, temp, pole);
  54.       System.out.println("Move disc " + n + " from pole " + from + " to pole " + to);
  55.       pole[n] = to;
  56.       draw(pole);
  57.       hanoi(n-1, temp, from, to, pole);
  58.    }
  59. IFS.java
  60.    public static void main(String[] args) {
  61.       int N = Integer.parseInt(args[0]);   // number of discs
  62.       int WIDTH  = 200;                    // width of largest disc
  63.       int HEIGHT = 20;                     // height of each disc
  64.  
  65.       // set size of window and sale
  66.       StdDraw.setCanvasSize(4*WIDTH, (N+3)*HEIGHT);
  67.       StdDraw.setXscale(-1, 3);
  68.       StdDraw.setYscale(0, N+3);
  69.  
  70.       // solve the Towers of Hanoi with N discs
  71.       hanoi(N);
  72.    }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement