How to resolve the algorithm Sierpinski triangle step by step in the Processing programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sierpinski triangle step by step in the Processing programming language

Table of Contents

Problem Statement

Produce an ASCII representation of a Sierpinski triangle of order   N.

The Sierpinski triangle of order   4   should look like this:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sierpinski triangle step by step in the Processing programming language

Source code in the processing programming language

void setup() {
  size(410, 230);
  background(255);
  fill(0);
  sTriangle (10, 25, 100, 5);
}
 
void sTriangle(int x, int y, int l, int n) {
    if( n == 0) text("*", x, y);
    else {
        sTriangle(x, y+l, l/2, n-1);
        sTriangle(x+l, y, l/2, n-1);
        sTriangle(x+l*2, y+l, l/2, n-1);
    }
}


void setup() {
  print(getSierpinskiTriangle(3));
}
String getSierpinskiTriangle(int n) {
  if ( n == 0 ) {
    return "*";
  }
  String s = getSierpinskiTriangle(n-1);
  String [] split = s.split("\n");
  int length = split.length;
  //  Top triangle
  String ns = "";
  String top = buildSpace((int)pow(2, n-1));
  for ( int i = 0; i < length; i++ ) {
    ns += top;
    ns += split[i];
    ns += "\n";
  }
  //  Two triangles side by side
  for ( int i = 0; i < length; i++ ) {
    ns += split[i];
    ns += buildSpace(length-i);
    ns += split[i];
    ns += "\n";
  }
  return ns.toString();
}

String buildSpace(int n) {
  String ns = "";
  while ( n > 0 ) {
    ns += " ";
    n--;
  }
  return ns;
}


  

You may also check:How to resolve the algorithm Josephus problem step by step in the Processing programming language
You may also check:How to resolve the algorithm Pentagram step by step in the Processing programming language
You may also check:How to resolve the algorithm Sierpinski carpet step by step in the Processing programming language
You may also check:How to resolve the algorithm Averages/Root mean square step by step in the Processing programming language
You may also check:How to resolve the algorithm Sieve of Eratosthenes step by step in the Processing programming language