March 5, 2011

Koch SnowFlake in Java

Here is some code for the koch snowflake written in java for a class I was taking.  It uses the StdDraw and Turtle graphics to draw the picture, and a little recursion.

Anyways, here's the code for the snowflake:

/**************************************************
 *  Compilation:  javac KochSnowFlake.java
 *  Execution:    java KochSnowFlake N
 *  Dependencies: StdDraw.java Turtle.java
 *
 *  Plot an order N Koch snowflake
 *
 *  % java KochSnowFlake 3
 *
 ***************************************************/


public class KochSnowFlake {
    private Turtle turtle;      // for turtle graphics
    private double size;        // size of each line segment

    public KochSnowFlake(int N) {
        int width = 512;
        int height = (int) (2 * width / Math.sqrt(3));
        size = width / Math.pow(3.0, N);
        turtle = new Turtle(0, width * Math.sqrt(3) / 2, 0.0);
        turtle.setCanvasSize(width, height);
        turtle.setXscale(0, width);
        turtle.setYscale(0, height);

        // three Koch curves in the shape of an equilateral triangle
        koch(N);
        turtle.turnLeft(-120);
        koch(N);
        turtle.turnLeft(-120);
        koch(N);
    }

    public void koch(int n) {
        if (n == 0) {
            turtle.goForward(size);
        }
        else {
            koch(n-1);
            turtle.turnLeft(60);
            koch(n-1);
            turtle.turnLeft(-120);
            koch(n-1);
            turtle.turnLeft(60);
            koch(n-1);
        }
    }

    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        new KochSnowFlake(N);
    }
}

Using  java KochSnowFlake 3 and java KochSnowFlake 4, I was able to generate the images required for the assignment:



You'll probably want these also...  Turtle.java and StdDraw.java.

3 comments: