in java a sierpinski Triangle is a fractal formed by drawing a triangle, A and t
ID: 3835456 • Letter: I
Question
in java
a sierpinski Triangle is a fractal formed by drawing a triangle, A and then using the mid of each side of triangle to form another triangle. This inner triangle is then removed. The result is three smaller triangles (one at the top and one in each corner) on which the process is repeated. After iteration N, the image will contain 3N triangles, each of which is similar to the origi- nal triangle. Write a program that implements a recursive algorithm for drawing a Sierpinski Triangle. The user interface for the program should include a Jslider that allows the user to select a value for N. The slider should allow the user to pic a value for N between 0 and the maximum value of N pos- sible based on the size of the program window. The maximum slider value should change as appropriate when the window is resized.
Explanation / Answer
public class Sierpinski { public static void sierpinski(int n) { sierpinski(n, 0, 0, 1); } public static void sierpinski(int n, double x, double y, double size) { if (n == 0) return; //compute triangle points double x0 = x; double y0 = y; double x1 = x0 + size; double y1 = y0; double x2 = x0 + size / 2; double y2 = y0 + (Math.sqrt(3)) * size / 2; // draw the triangle StdDraw.line(x0, y0, x1, y1); StdDraw.line(x0, y0, x2, y2); StdDraw.line(x1, y1, x2, y2); StdDraw.show(100); //recursive calls sierpinski(n-1, x0, y0, size / 2); sierpinski(n-1, (x0 + x1) / 2, (y0 + y1) / 2, size / 2); sierpinski(n-1, (x0 + x2) / 2, (y0 + y2) / 2, size / 2); } // read in a command-line argument n and plot an order Sierpinski Triangle public static void main(String[] args) { int n = Integer.parseInt(args[0]); StdDraw.setPenRadius(0.005); sierpinski(n); } }
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.