Created
December 2, 2011 22:18
-
-
Save ehayon/1425086 to your computer and use it in GitHub Desktop.
Koch Snowflake
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package recursion; | |
import cos126.StdDraw; | |
import java.awt.geom.*; | |
import java.lang.Math; | |
public class KochSnowflake | |
{ | |
public static Point2D.Double ref; | |
public static int rotation = 0; | |
public static int side_rotation = 0; | |
public static int current_turn = 60; | |
public static void main(String[] args) | |
{ | |
StdDraw.setXscale(0, 130); | |
StdDraw.setYscale(0, 100); | |
int n = Integer.parseInt(args[0]); | |
double size = (25/Math.pow(3.0, n)); | |
ref = new Point2D.Double(10, 80); | |
System.out.println("Size: " + size); | |
turn(0); | |
koch(n, size); | |
side_rotation = -120; | |
koch(n, size); | |
side_rotation = -240; | |
koch(n, size); | |
side_rotation = 0; | |
} | |
static void koch(int n, double size) | |
{ | |
if (n == 0) | |
{ | |
draw_line(ref, size); | |
} | |
else | |
{ | |
current_turn = 0; | |
koch(n-1, size); | |
turn(60); | |
koch(n-1, size); | |
turn(-60); | |
koch(n-1, size); | |
turn(0); | |
koch(n-1, size); | |
} | |
} | |
static void draw_line(Point2D.Double p1, double size) | |
{ | |
Point2D.Double p2 = new Point2D.Double(p1.x + size*Math.cos((rotation+current_turn+side_rotation)*((Math.PI)/180)), (p1.y + size*Math.sin((rotation+current_turn+side_rotation)*((Math.PI)/180)))); | |
StdDraw.line(p1.x, p1.y, p2.x, p2.y); | |
ref = p2; | |
} | |
static void turn(int rot) | |
{ | |
rotation = rot; | |
} | |
static int getTurn() { | |
return rotation; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment