Reading time: about 1 minute
Over the years I’ve written a number of little apps to help people understand how different algorithms work. I’ve gotten a lot of positive feedback about them from students and teachers, and a few have been featured in magazines or books. So I thought it would be a worthwhile exercise to port at least some of these to run in a browser. To start the project off, though, I wanted to do something that was more fun than functional. This is the result.
Part of the magic that draws people into programming is the incredible complexity and beauty that can result from taking a few simple instructions and letting them run wild. The most immediate and tangible form of this magic is certainly the “display hack,” a small program that makes pretty pictures. Even A.K. Dewdney’s classic tour of computing science, The Turing Omnibus, starts with a display hack which he describes as algorithmic wallpaper. That seems as good a way to kick things off as any, so here’s a version of it—with one small modification: the original produced two-colour images, while this version allows a variable number. Here’s the pseudocode:
for i := 1 to imageWidth for j := 1 to imageHeight x := originX + i × sideLength / imageWidth y := originY + j × sideLength / imageHeight c := floor( x2 + y2 ) mod numberOfColours plot( i, j, colourc ) end for end for
And here’s an implementation. Changing the values used for the sideLength, origin, or numberOfColours will produce different pictures; colour is a list of colours from 0 to numberOfColours-1. Setting this to 2 will recreate Dewdney’s original black-and-white version. This version uses a simple colour gradient, but you could easily make that more exciting.