The Koch Snowflake

The Koch Snowflake is more complicated than the Sierpinski or the H-Tree fractals---it may even be more complicated than the Tree Fractal, since it doesn't use tail recursion (where you recurse at the end of the method). Think about drawing line segments, where a segment is the side of a triangle. Each time you draw a segment, you actually break that segment up into pieces: you draw a segment over the "first" 1/3 of the edge, a segment over the "second" 1/3 of the edge, and then a pair of shorter segment to form the new triangle. Each of these segments is a recursive call, unless you've hit the maximum number of steps (the "end" of your recursion), in which case you can just draw a straight line instead. See the below figure for an example.

Figure from Wikipedia (you do not need to draw the green lines).

The only things you'll need to draw the Koch snowflake are the starting x and y coordinates of the side of each triangle. Note that you'll need to keep your points in "order," so that you build your fractal out instead of in. You will also want to keep track of how many iterations you have gone through, so that you can stop (4 or 5 ended up being a good number for me). So overall, the signature for your recursive method might look like this:

public void drawSegment(int x1, int y1, int x2, int y2, int iterations)

Note that you can find the end points that are 1/3 and 2/3 of the way through the segment easily; simply divide (x2-x1) by 3.

Finding the new, outside point to draw the growing triangle is trickier, but some simple trigonometry can show us that it should be at:

[x1 + 0.5 * (x2 - x1) + sqrt(3)*(y2-y1)/6.0, 
 y1 + 0.5 * (y2 - y1) - sqrt(3)*(x2-x1)/6.0]

Again, make sure that you keep your points in order so you build out instead of in!