Write an A5Q1 class containing a main method calling a recursive method to draw
ID: 3865542 • Letter: W
Question
Write an A5Q1 class containing a main method calling a recursive method to draw Sierpinski triangles (http://en.wikipedia.or are equilateral triangles that can be drawn recursively. You will use the StdDraw class to draw the triangles ski triangle). Sierpinski triangles 3.2 THE DRAWTRIANGLES METHODS Define two drawTriangles methods, one non-recursive, and one recursive method. The non-recursive version simply calls the recursive version. The recursive version will draw a "level n" Sierpinski triangle. A "level 1" triangle is just an ordinary equilateral triangle. A “level n" triangle is made up of three smaller "level n-1" Sierpinski triangles, as defined below.Explanation / Answer
Here is the code segment as per given criteria, please go through it thoroughly:-
import java.awt.*;
import java.util.*;
public class Sierpinski_Triangle {
public static final int TreeSize = 512; // height/width of Drawing_Panel
public static void main(String[] args) {
// promt for level
Scanner scan = new Scanner(System.in);
System.out.print("Enter the level: ");
int level = scan.nextInt();
Drawing_Panel dp = new Drawing_Panel(TreeSize, TreeSize);
dp.setBackground(Color.Pink);
Graphics gr = dp.getGraphics();
// calculate triangle endpoint and start the recursion
int currentSideLength = (int) Math.round(TreeSize * Math.sqrt(3.0) / 2.0);
Point pt1 = new Point(0, currentSideLength);
Point pt2 = new Point(TreeSize / 2, 0);
Point pt3 = new Point(TreeSize, currentSideLength);
draw_Figure(level, gr, pt1, pt2, pt3);
}
public static void draw_Figure(int level, Graphics g,
Point pt1, Point pt2, Point pt3) {
if (level == 1) {
// codes for single triangle
Polygon p = new Polygon();
p.addPoint(pt1.x, pt1.y);
p.addPoint(pt2.x, pt2.y);
p.addPoint(pt3.x, pt3.y);
g.fillPolygon(p);
} else {
// recursive call into 3 triangles
Point pt4 = midpoint(pt1, pt2);
Point pt5 = midpoint(pt2, pt3);
Point pt6 = midpoint(pt1, pt3);
draw_Figure(level - 1, g, pt1, pt4, pt6);
draw_Figure(level - 1, g, pt4, pt2, pt5);
draw_Figure(level - 1, g, pt6, pt5, pt3);
}
}
public static Point midpoint(Point pt1, Point pt2) {
return new Point((pt1.x + pt2.x) / 2, (pt1.y + pt2.y) / 2);
}
}
=============================================
Please run these codes into your window and checkout the output.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.