Tuesday, September 10, 2013

Sierpiinski Triangle / Gasket

SierpiinskiTriangle.java 

Sierpiinski Triangle

import java.awt.*;
import java.applet.*;

/*
<applet code=SierpiinskiTriangle height=300 width=500>
</applet>
*/
public class SierpiinskiTriangle extends Applet 
{
public SierpiinskiTriangle(){
}
public void paint(Graphics g){
super.paint(g);
int x[] = { 50 ,0,100}; 
int y[] = {  0 ,100,100};
g.setColor(Color.black);
g.fillPolygon (x, y, 3);
for(int i=0;i<5;i++){
int x1[] = { 150+(i*100) ,100+(i*100),200+(i*100)}; 
int y1[] = { 0 ,100,100};
g.setColor(Color.black);
g.fillPolygon (x1, y1, 3);
g.setColor(Color.white);
makeTriangle(g, x1[0],y1[0], x1[1], y1[1], x1[2], y1[2], i);
}
 
}
public void makeTriangle(Graphics g, int x1, int y1, int x2, int y2, int x3, int y3, int level) {
      // Compute the points
      int[] xPoints = new int[3];
      int[] yPoints = new int[3];
      int xMid12;
      int xMid23;
      int xMid31;
      int yMid12;
      int yMid23;
      int yMid31;
      // Compute midpoints of triangle sides
      xMid12 = (x1 + x2) / 2;
      xMid23 = (x2 + x3) / 2;
      xMid31 = (x3 + x1) / 2;
      yMid12 = (y1 + y2) / 2;
      yMid23 = (y2 + y3) / 2;
      yMid31 = (y3 + y1) / 2;
      xPoints[0] = xMid12;
      xPoints[1] = xMid23;
      xPoints[2] = xMid31;
      yPoints[0] = yMid12;
      yPoints[1] = yMid23;
      yPoints[2] = yMid31;
      // Fill the triangle
      g.fillPolygon(xPoints, yPoints, 3);
      // Recursively draw three smaller triangles if level > 0
      if (level > 0) {
        g.setColor(Color.white);
        makeTriangle(g, x1, y1, xMid12, yMid12, xMid31, yMid31, level - 1);
        makeTriangle(g, xMid12, yMid12, x2, y2, xMid23, yMid23, level - 1);
        makeTriangle(g, xMid31, yMid31, xMid23, yMid23, x3, y3, level - 1);
      }
}


}

No comments:

Post a Comment