Back to Basics – Sierpinski Triangle

I remember back when I was first learning C, and one of the assignments was to draw the Sierpinski Triangle. I didn’t know what it was, but sequential steps were given to iteratively create it. The steps were roughly like so:

  • Generate a triangle on a plane with 3 points
  • Set the centre of the triangle as the current point
  • Randomly select one of the triangle points
  • Get the mid-point between the current point and the selected point
  • Plot the mid-point and set it as the current point
  • Randomly select one of the triangle points
  • Get the mid-point between the current point and the selected point
  • Plot the mid-point and set it as the current point
  • Continue till iteration limit is reached

I was told to visualise the plane as a matrix, and the plotted points were to be printed as asterisks on the screen.

It’s been years now, and I still think the screen output of my Sierpinski Triangle sucked because of the low resolution. Now, older and wiser, I can come up with a better representation.
Sierpinski Triangle

Download the full source code.

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;

namespace b2bSierpinskiTriangle
{
    class Program
    {
        static void Main(string[] args)
        {
            const int cnSize = 512;
            const int cnLimit = 50000;
            int[,] points = new int[3, 2];
            points[0, 0] = cnSize / 2;
            points[0, 1] = 10;
            points[1, 0] = 10;
            points[1, 1] = cnSize - 16;
            points[2, 0] = cnSize - 16;
            points[2, 1] = cnSize - 16;
            Bitmap bm = new Bitmap(cnSize, cnSize);
            Graphics g = Graphics.FromImage(bm);
            g.FillRectangle(Brushes.White, 0, 0, cnSize, cnSize);
            int trianglepoint = 0;
            Random rand = new Random();
            int currentx = 0, currenty = 0;
            int previousx = cnSize / 2, previousy = cnSize / 2;
            for (int i = 0; i < cnLimit; ++i)
            {
                trianglepoint = rand.Next(3);
                currentx = (points[trianglepoint, 0] + previousx) / 2;
                currenty = (points[trianglepoint, 1] + previousy) / 2;
                bm.SetPixel(currentx, currenty, Color.Navy);
                previousx = currentx;
                previousy = currenty;
            }
            bm.Save("sierpinski.bmp");
            g.Dispose();
            bm.Dispose();
        }
    }
}

Short and sweet. Instead of printing to the command line screen, I plotted the points to a bitmap. I still remember printing my program listing and the Sierpinski asterisks output. Though pleased with the required output, I thought it looked a little unrefined around the edges.

Printing to a bitmap at pixel level makes it look much better…

Comments are closed.