KochRainbow.java


Below is the syntax highlighted version of KochRainbow.java from §2.7 Recursion.

/*************************************************************************
 *  Compilation:  javac KochRainbow.java
 *  Execution:    java KochRainbow N
 *  Dependencies: StdDraw.java
 *  
 *  Plot an order N Koch snowflake, using the spectrum of colors.
 *
 *  % java Koch 5
 *
 *************************************************************************/

import java.awt.Color;

public class KochRainbow {

   public static void koch(int n, double size, double color, double increment) {
      if (n == 0) {
         StdDraw.setColorHSB(color, 1.0, 1.0);
         color = color + increment;
         StdDraw.goForward(size);
         StdDraw.pause(10);
      }
      else {
         koch(n-1, size, color, increment);
         StdDraw.rotate(60);
         koch(n-1, size, color, increment);
         StdDraw.rotate(-120);
         koch(n-1, size, color, increment);
         StdDraw.rotate(60);
         koch(n-1, size, color, increment);
     }
   }

   public static void main(String args[]) {
      int N = Integer.parseInt(args[0]);
      int width = 512;
      int height = (int) (2 * width / Math.sqrt(3));
      double size = width / Math.pow(3.0, N);

      // rainbow of colors
      double color = 0.0;
      double increment = Math.pow(4.0, -N) / 3.0;

      StdDraw.create(width, height);
      StdDraw.go(0, width * Math.sqrt(3) / 2);
      StdDraw.penDown();
      koch(N, size, color, increment);
      StdDraw.rotate(-120);
      koch(N, size, color, increment);
      StdDraw.rotate(-120);
      koch(N, size, color, increment);
      StdDraw.show();
   }
}


Last updated: Sun Sep 26 12:24:04 EDT 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.