Skip to content

Instantly share code, notes, and snippets.

@henryefranks
Created September 9, 2018 22:58
Show Gist options
  • Save henryefranks/8ae05530fb3d8dede86cc74accac411c to your computer and use it in GitHub Desktop.
Save henryefranks/8ae05530fb3d8dede86cc74accac411c to your computer and use it in GitHub Desktop.
Sierpinski triangle generator in C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[]) {
int layers = 16; // Default value
if (argc > 1) { // Optional layers input
layers = atoi(argv[1]);
if (layers < 1) {
printf("Please supply a valid number of layers\n");
return 1;
}
}
// Only the current and previous layers are needed
int nodes[2][layers];
for (int len = 0; len < layers; len++) {
for (int i = len; i < layers; i++) {
printf(" "); // Padding to shape the tree
}
for (int i = 0; i <= len; i++) {
if (i == 0 || i == len) {
// If the node is on the edge it will always branch
nodes[1][i] = 1;
} else {
// The node will only branch it both parent branches are different
nodes[1][i] = nodes[0][i-1] ^ nodes[0][i];
}
if (nodes[1][i]) {
printf("/\\");
} else {
printf(" ");
}
}
// Copy the current to the previous layer
memcpy(nodes[0], nodes[1], 4*layers);
printf("\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment