How to resolve the algorithm Sierpinski square curve step by step in the Go programming language

Published on 12 May 2024 09:40 PM
#Go

How to resolve the algorithm Sierpinski square curve step by step in the Go programming language

Table of Contents

Problem Statement

Produce a graphical or ASCII-art representation of a Sierpinski square curve of at least order 3.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sierpinski square curve step by step in the Go programming language

The given Go program uses the lindenmayer package to generate and render the Sierpinski square curve fractal. Here's a detailed explanation:

  1. Package and Imports:

    • The program uses the github.com/fogleman/gg package for drawing and the github.com/trubitsyn/go-lindenmayer package for implementing L-systems.
  2. Constants and Variables:

    • twoPi is set to the value of 2π (2 * math.Pi).
    • width and height represent the dimensions of the output image (770x770 pixels).
    • dc is a gg.Context object used for drawing.
  3. Initialization:

    • The background of the image is set to blue using dc.SetRGB(0, 0, 1).
    • The context is cleared using dc.Clear().
    • cx and cy are set to the starting coordinates, and h is set to the length of each line segment.
    • theta is initialized to zero, representing an initial angle of 0 degrees.
  4. L-System Definition:

    • An L-system sys is defined with the following properties:
      • Variables: ['X']
      • Constants: ['F', '+', '-']
      • Axiom: "F+XF+F+XF"
      • Rules: ["X" -> "XF-F+F-XF+F+XF-F+F-X"]
      • Angle: π/2 (90 degrees in radians)
  5. L-System Iteration:

    • Iterate function from the go-lindenmayer package is used to generate the result string by iterating the L-system 5 times.
  6. Drawing Operations:

    • A map called operations is defined to associate each symbol in the L-system with a drawing operation:
      • 'F': Draw a line segment of length h in the current direction.
      • '+': Rotate clockwise by the angle specified in the L-system.
      • '-': Rotate counterclockwise by the angle specified in the L-system.
  7. Symbol Processing:

    • The generated L-system result (string) is processed using Process from the go-lindenmayer package. For each symbol in the result, the corresponding drawing operation from the operations map is executed.
  8. Additional Drawing:

    • After processing the L-system, additional drawing operations are performed to close the square at the extreme left.
  9. Image Creation and Saving:

    • The drawing context dc is set to draw in yellow.
    • The line width is set to 2, and the curve is drawn using dc.Stroke().
    • The image is saved to a PNG file named "sierpinski_square_curve.png" using dc.SavePNG().

In summary, this program defines and iterates an L-system to generate the Sierpinski square curve, then uses the gg library to draw and save the curve as an image. The go-lindenmayer package is utilized for L-system-related operations like iteration and symbol processing.

Source code in the go programming language

package main

import (
    "github.com/fogleman/gg"
    "github.com/trubitsyn/go-lindenmayer"
    "log"
    "math"
)

const twoPi = 2 * math.Pi

var (
    width  = 770.0
    height = 770.0
    dc     = gg.NewContext(int(width), int(height))
)

var cx, cy, h, theta float64

func main() {
    dc.SetRGB(0, 0, 1) // blue background
    dc.Clear()
    cx, cy = 10, height/2+5
    h = 6
    sys := lindenmayer.Lsystem{
        Variables: []rune{'X'},
        Constants: []rune{'F', '+', '-'},
        Axiom:     "F+XF+F+XF",
        Rules: []lindenmayer.Rule{
            {"X", "XF-F+F-XF+F+XF-F+F-X"},
        },
        Angle: math.Pi / 2, // 90 degrees in radians
    }
    result := lindenmayer.Iterate(&sys, 5)
    operations := map[rune]func(){
        'F': func() {
            newX, newY := cx+h*math.Sin(theta), cy-h*math.Cos(theta)
            dc.LineTo(newX, newY)
            cx, cy = newX, newY
        },
        '+': func() {
            theta = math.Mod(theta+sys.Angle, twoPi)
        },
        '-': func() {
            theta = math.Mod(theta-sys.Angle, twoPi)
        },
    }
    if err := lindenmayer.Process(result, operations); err != nil {
        log.Fatal(err)
    }
    // needed to close the square at the extreme left
    operations['+']()
    operations['F']()

    // create the image and save it
    dc.SetRGB255(255, 255, 0) // yellow curve
    dc.SetLineWidth(2)
    dc.Stroke()
    dc.SavePNG("sierpinski_square_curve.png")
}


  

You may also check:How to resolve the algorithm Hofstadter Q sequence step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Runtime evaluation/In an environment step by step in the TXR programming language
You may also check:How to resolve the algorithm Truth table step by step in the Pascal programming language
You may also check:How to resolve the algorithm Nth root step by step in the Erlang programming language
You may also check:How to resolve the algorithm Twin primes step by step in the Applesoft BASIC programming language