Java Reference
In-Depth Information
private
Point midPoint(Point pOne, Point pTwo)
{
Point mid =
new
Point((pOne.x + pTwo.x) / 2,
(pOne.y + pTwo.y) / 2);
return
mid;
}
The recursive algorithm to draw a Sierpinski gasket is as follows:
Base case: If the level is
0
, draw the first triangle.
Recursive case: If the level is greater than
0
, then for each triangle in the Sierpinski
gasket, find the midpoints of the sides and draw lines through those points.
Suppose that
p1
,
p2
, and
p3
are the three vertices of a triangle, and
lev
denotes the
number of levels of the Sierpinski gasket to be drawn. The following method
implements the recursive algorithm to draw a Sierpinski gasket:
private void
drawSierpinski(Graphics g,
int
lev,
Point p1, Point p2, Point p3)
{
Point midP1P2;
Point midP2P3;
Point midP3P1;
if
(lev > 0)
{
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.drawLine(p2.x, p2.y, p3.x, p3.y);
g.drawLine(p3.x, p3.y, p1.x, p1.y);
midP1P2 = midPoint(p1, p2);
midP2P3 = midPoint(p2, p3);
midP3P1 = midPoint(p3, p1);
drawSierpinski(g, lev - 1, p1, midP1P2, midP3P1);
drawSierpinski(g, lev - 1, p2, midP2P3, midP1P2);
drawSierpinski(g, lev - 1, p3, midP3P1, midP2P3);
}
}
The following program listing provides the complete algorithm to draw a Sierpinski
gasket of a given order. Notice that the program uses an input dialog box to get the
user's input.
Search WWH ::
Custom Search