I am fascinated by some of the early algorithms that were developed before the day of computers. I have decided to pick some interesting algorithms and implement them in one of the higher level programming languages.
The first interesting thing I came across is the Sierpinski Gasket or Sierpinski Triangle. I made it my first challenge to write program that can draw the triangle for me. I chose to write the program in Java, JavaFx to be specific.
Since the Sierpinski Triangle is a repetitive structure I found it intuitive to write a recursive function that generates the triangle. The algorithm was not difficult to design. I started with one big triangle and removed the center triangle and repeated this for the remaining 3 triangles.
The other thing I included was a limit to the length of the triangle edges so that my program can halt.
Enough about talking now here is the code
private void sierpinskiTriangle(Group root,
Polygon shape,
double limitLength) {
List<Double> list = shape.getPoints();
Double[] points = new Double[6];
points = list.toArray(points);
if (distance(points[0], points[2], points[1], points[3]) < limitLength) {
return;
}
numTriangles++;
int size = points.length;
if (size == 6) // triables
{
//find midpoints
Double[] midpoints = new Double[6];
for (int i = 0; i < size; ++i) {
if (i < size - 2) {
midpoints[i] = (points[i] + points[i + 2]) / 2;
} else {
midpoints[i] = (points[i] + points[2 - (points.length - i)]) / 2;
}
}
Polygon poly = PolygonBuilder.create().points(midpoints).fill(Color.WHITE).build(); // middle triangle
root.getChildren().add(poly);
Polygon poly1 = PolygonBuilder.create().points(points[0], points[1], midpoints[0], midpoints[1], midpoints[4], midpoints[5]).build();
Polygon poly2 = PolygonBuilder.create().points(midpoints[0], midpoints[1], points[2], points[3], midpoints[2], midpoints[3]).build();
Polygon poly3 = PolygonBuilder.create().points(midpoints[4], midpoints[5],points[4], points[5], midpoints[2], midpoints[3]).build();
sierpinskiTriangle(root, poly1, limitLength);
sierpinskiTriangle(root, poly2, limitLength);
sierpinskiTriangle(root, poly3, limitLength);
}
else
{
System.out.println("not equal to 6");
}
}
I assume the code is self explanatory for now. My next installation will consist of an animated approach