Thursday, 25 November 2010

Picture this - programming for fun

As I said only last year, when I started programming I used to play around with graphics. So here are a couple of programming problems based around graphics, and specifically around the Sierpinski triangle.

Random motion within a triangle

What do you get if you put the following recipe together?

(1) Draw an equilateral triangle and label the corners A, B and C
(2) Set your current position, P, to corner A.
(3) Choose one of the three corners at random and move P halfway to that corner.
(4) Draw a dot at the new location of P.
(5) Go back to 3 (Repeat 500 or 1000 times in total)

Apparently, this is called the Chaos game. If you follow the links on the Wikipedia page I linked to, it seems that the same method could be used to draw a fern fractal.

Triangles within triangles

This one is a bit tricky in terms of programming as you need to learn about recursion (functions that call themselves). It's not rocket science but it's a bit confusing first time you see it. Not to worry - let's just plough ahead anyway :-)

(0) Draw a white equilateral triangle of length M (some value) pointing upwards centered around a point N (some point in the middle of the screen).
(1) Write a function that takes a point on the screen, P, and a length, L, and draws an upside-down black equilateral triangle centered around P with sides of length L. For example, if this function is called with L=M/2 and with P=N, this should leave three white equilateral triangles on the screen (separated by the black one).
(2) The second thing the function should do is if L > M/16, it should call itself three separate times to draw three black triangles of length L/2 centred in the middle of each of the three white equilateral triangles around it.
(3) Now, back in the main part of the program, call the function you've just written using N for the value of P, and M/2 for the value of L.

If you get this working, this is a fun program to play around with. What happens if you use squares or circles? Another related structure is the Koch snowflake: there's a recipe at Wikipedia.

Pascal's Triangle

Pascal's Triangle is a triangle of numbers that looks like this:

1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1

Each new row is created by adding the two numbers in the row above it.

To turn this into a nice graphic, create the first 1000 or so rows of the triangle, and draw it on the screen by using a white dot for the odd numbers, and a black dot for the evens.

Image credit: chelmsfordpubliclibrary

No comments: