-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKochSnowflake.java
More file actions
45 lines (36 loc) · 1.19 KB
/
KochSnowflake.java
File metadata and controls
45 lines (36 loc) · 1.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Koch Snowflake implementation.
*/
public class KochSnowflake {
private static final int ORDER = 6;
public static void koch(double x1, double y1, double x2, double y2, int n) {
if (n == 0) {
StdDraw.line(x1, y1, x2, y2);
return;
}
double dx = (x2 - x1) / 3.0;
double dy = (y2 - y1) / 3.0;
double xA = x1 + dx;
double yA = y1 + dy;
double xB = x1 + 2 * dx;
double yB = y1 + 2 * dy;
double xPeak = xA + (dx - Math.sqrt(3) * dy) / 2.0;
double yPeak = yA + (dy + Math.sqrt(3) * dx) / 2.0;
koch(x1, y1, xA, yA, n - 1);
koch(xA, yA, xPeak, yPeak, n - 1);
koch(xPeak, yPeak, xB, yB, n - 1);
koch(xB, yB, x2, y2, n - 1);
}
public static void main(String[] args) {
StdDraw.setCanvasSize(800, 800);
StdDraw.setXscale(-0.1, 1.1);
StdDraw.setYscale(-0.1, 1.1);
// Equilateral triangle
double x1 = 0.1, y1 = 0.2;
double x2 = 0.9, y2 = 0.2;
double x3 = 0.5, y3 = 0.2 + Math.sqrt(3) / 2 * 0.8;
koch(x1, y1, x2, y2, ORDER);
koch(x2, y2, x3, y3, ORDER);
koch(x3, y3, x1, y1, ORDER);
}
}