English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I need to make a programme that works out the coordinates of the white triangles, given an original (larger) black triangle for a Sierpinski Gasket. I know I need to use recursion.

At the moment, I have a structure which holds the coordinates of the vertices of the black triangle, and I know how to calculate the coordinates by hand... but I don't know how to get the computer to define 3 new black triangles each time a white one is created (up to some user-defined maximum depth).

Help me out, please.

2007-03-11 23:10:01 · 1 answers · asked by sarciness 3 in Computers & Internet Programming & Design

1 answers

This is where the recursion comes in. Make the function that calculates the coordinates accept a pointer to a black triangle structure as a parameter that defines the black triangle to work on. In this same function, declare a second (non static) variable of the same type as your original black triangle structure, for storing the triangles for the next iteration. First calculate the coordinates of the white triangle, then use these coordinates to find the coordinates of each of the three black triangles in turn. Each of the black triangles will have one coordinate matching the original triangle, and the other two will match two of the coordinates of the white triangle.

Each time you find the coordinates of one of the three black triangles in the function, store the coordinates in the second black triangle structure you defined, and make the function call itself recursively using the address of this second structure as the parameter.

The final thing you need to do is limit the maximum depth of the recursion. You can do this using a global or static variable that defines the depth. Set it to zero before first calling the function, then at the beginning of the function, check if this variable has exceeded the maximum depth. If it has, return from the function, otherwise increase the depth by one, go through with the function and decrease the depth by one again at the very end of the function.

2007-03-12 00:35:27 · answer #1 · answered by Groucho Returns 5 · 0 0

fedest.com, questions and answers