How to resolve the algorithm Sierpinski pentagon step by step in the Java programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sierpinski pentagon step by step in the Java programming language

Table of Contents

Problem Statement

Produce a graphical or ASCII-art representation of a Sierpinski pentagon (aka a Pentaflake) of order 5. Your code should also be able to correctly generate representations of lower orders: 1 to 4.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sierpinski pentagon step by step in the Java programming language

The provided code is designed to visualize the generation of a Sierpinski pentagon, which is a fractal pattern that exhibits self-similarity. It primarily consists of the following:

  1. Import Statements: The code begins by importing the necessary packages for creating graphical user interfaces and manipulating colors.

  2. SierpinskiPentagon Class:

    • This is the main class responsible for creating the fractal image and includes the following:
    • Constants: Various constants are defined to control the scaling, angles, and margins of the pentagons.
    • Constructor: The constructor initializes the panel's preferred size, background color, and sets up a timer to incrementally increase the depth of the fractal over time.
    • drawPentagon Method: This method takes several parameters and draws a single pentagon. Here's how it works:
      • If the depth is 0 (the base case), it creates a Path2D and defines the vertices of the pentagon based on the provided coordinates, side length, and angle. It then fills the shape with a random hue.
      • If the depth is greater than 0, it calculates the scaled side length and the distance between the vertices of the pentagons in the next level.
      • The method then recursively calls itself to draw the pentagons in the next level, moving around the virtual pentagon formed by their top vertices.
    • paintComponent Method: This method is called by the system to paint the component. It sets some rendering hints for anti-aliasing, calculates the radius and side length of the base pentagon, and calls the drawPentagon method to draw the initial pentagon with the specified depth.
  3. main Method:

    • This is the entry point of the program. It sets up the GUI using Swing and creates a JFrame with the SierpinskiPentagon as its content pane.
  4. RandomHue Class:

    • This class is used to generate random colors for the pentagons and employs a golden ratio conjugate algorithm to avoid clustering of similar colors.

Overall, the code demonstrates the creation of a Sierpinski pentagon fractal, which is an interesting example of how complex patterns can emerge from simple rules. When run, the program generates a dynamic fractal image where the depth of the fractal increases over time.

Source code in the java programming language

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.geom.Path2D;
import static java.lang.Math.*;
import java.util.Random;
import javax.swing.*;

public class SierpinskiPentagon extends JPanel {
    // exterior angle
    final double degrees072 = toRadians(72);

    /* After scaling we'll have 2 sides plus a gap occupying the length
       of a side before scaling. The gap is the base of an isosceles triangle
       with a base angle of 72 degrees. */
    final double scaleFactor = 1 / (2 + cos(degrees072) * 2);

    final int margin = 20;
    int limit = 0;
    Random r = new Random();

    public SierpinskiPentagon() {
        setPreferredSize(new Dimension(640, 640));
        setBackground(Color.white);

        new Timer(3000, (ActionEvent e) -> {
            limit++;
            if (limit >= 5)
                limit = 0;
            repaint();
        }).start();
    }

    void drawPentagon(Graphics2D g, double x, double y, double side, int depth) {
        double angle = 3 * degrees072; // starting angle

        if (depth == 0) {

            Path2D p = new Path2D.Double();
            p.moveTo(x, y);

            // draw from the top
            for (int i = 0; i < 5; i++) {
                x = x + cos(angle) * side;
                y = y - sin(angle) * side;
                p.lineTo(x, y);
                angle += degrees072;
            }

            g.setColor(RandomHue.next());
            g.fill(p);

        } else {

            side *= scaleFactor;

            /* Starting at the top of the highest pentagon, calculate
               the top vertices of the other pentagons by taking the
               length of the scaled side plus the length of the gap. */
            double distance = side + side * cos(degrees072) * 2;

            /* The top positions form a virtual pentagon of their own,
               so simply move from one to the other by changing direction. */
            for (int i = 0; i < 5; i++) {
                x = x + cos(angle) * distance;
                y = y - sin(angle) * distance;
                drawPentagon(g, x, y, side, depth - 1);
                angle += degrees072;
            }
        }
    }

    @Override
    public void paintComponent(Graphics gg) {
        super.paintComponent(gg);
        Graphics2D g = (Graphics2D) gg;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                RenderingHints.VALUE_ANTIALIAS_ON);

        int w = getWidth();
        double radius = w / 2 - 2 * margin;
        double side = radius * sin(PI / 5) * 2;

        drawPentagon(g, w / 2, 3 * margin, side, limit);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setTitle("Sierpinski Pentagon");
            f.setResizable(true);
            f.add(new SierpinskiPentagon(), BorderLayout.CENTER);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        });
    }
}

class RandomHue {
    /* Try to avoid random color values clumping together */
    final static double goldenRatioConjugate = (sqrt(5) - 1) / 2;
    private static double hue = Math.random();

    static Color next() {
        hue = (hue + goldenRatioConjugate) % 1;
        return Color.getHSBColor((float) hue, 1, 1);
    }
}


  

You may also check:How to resolve the algorithm MD4 step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Shell one-liner step by step in the Nim programming language
You may also check:How to resolve the algorithm Range extraction step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Seven-sided dice from five-sided dice step by step in the Erlang programming language
You may also check:How to resolve the algorithm Find the missing permutation step by step in the Quackery programming language