Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sierpinski Triangle and Carpet
package klausur.spierpinski;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
public class Sierpinski extends JPanel {
protected int order;
public Sierpinski(final int order) {
this.order = order;
}
@NotNull
private static Point midpoint(@NotNull final Point p1, @NotNull final Point p2) {
return new Point((p1.x + p2.x) / 2, (p1.y + p2.y) / 2);
}
public static void main(@Nullable final String[] args) {
final JFrame frame = new JFrame("Sierpinkski");
final Container container = frame.getContentPane();
container.add(new Sierpinski(5));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void drawTriangles(@NotNull final Graphics g, @NotNull final int width, @NotNull final int height) {
Point p1 = new Point(width / 2, 10);
Point p2 = new Point(10, height - 10);
Point p3 = new Point(width - 10, height - 10);
displayTriangles(g, order, p1, p2, p3);
}
private void displayTriangles(@NotNull final Graphics g, @NotNull final int order, final Point p1, @NotNull final Point p2, @NotNull final Point p3) {
if (order == 0) {
g.drawLine(p1.x, p1.y, p2.x, p2.y);
g.drawLine(p1.x, p1.y, p3.x, p3.y);
g.drawLine(p2.x, p2.y, p3.x, p3.y);
} else {
final Point p12 = midpoint(p1, p2);
final Point p23 = midpoint(p2, p3);
final Point p31 = midpoint(p3, p1);
// Recursively display three triangles
displayTriangles(g, order - 1, p1, p12, p31);
displayTriangles(g, order - 1, p12, p2, p23);
displayTriangles(g, order - 1, p31, p23, p3);
}
}
public void drawSierpinskiCarpet(@NotNull final Graphics g, @NotNull final int xOL, @NotNull final int yOL, @NotNull final int width, int height) {
if (width > 2 && height > 2) {
int b = width / 3;
int h = height / 3;
g.fillRect(xOL + b, yOL + h, b, h);
for (int k = 0; k < 9; k++)
if (k != 4) {
int i = k / 3;
int j = k % 3;
drawSierpinskiCarpet(g, xOL + i * b, yOL + j * h, b, h); // Rekursion
}
}
}
@Override
public void paintComponent(final Graphics g) {
super.paintComponent(g);
drawTriangles(g, getWidth(), getHeight());
drawSierpinskiCarpet(g, 0, 0, getWidth(), getHeight());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.