Chapter 12: Recursion 247
Modifying the Koch Snowflake
The Koch snowflake is a fractal generated by starting with 3 line sements forming an equilateral triangle
(a Koch fractal of order 1). The algorithm for generating higher order Koch fractals involves splitting each line
segment into three equal segments then replacing the middle segment by two line segments that protrude
outward. The same algorithm is then recursively applied to each of the 4 new line segments. In the basic Koch
the program in the appletviewer to see how it works (you may use the file Koch.html to run the program). In this
exercise you will generalize the pattern to allow for triangles other than equilateral ones to be built on the
middle third segment. In the drawFractal method this involves changing the calculation of x3 and y3, the
coordinates of the protrusion point. The following calculations are equivalent to those currently in the program:
where cosine is the cosine of 60 degrees (which is 1/2) and sine is the sine of 60 degrees (which is the square
root of 3 over 2). These equations are generalizable to angles other than 60. In this exercise you will generalize
the program to work for angles other than 60. The angle will be controlled by increase and decrease buttons in
1. In KochPanel.java,
Add instance variables angle, sine, and cosine. Angle will be an integer and sine and cosine type
2. Compile and run the program. It should behave just as before.
3. To add controls to allow the angle to change, do the following:
In KochPanel, add two public methods getAngle() that returns the angle (type int), and setAngle (int
newAngle) that sets the angle to be the value of newAngle and sets sine and cosine of that angle.
to 480.
The method actionPerformed must be modified to take action if the event source was one of the new
4. Compile and run the program. Play with the angles and order to see what fractal patterns are generated.