Click to See Complete Forum and Search --> : Recursion


Risifo
June 6th, 2002, 07:12 AM
Hey, i'm having a big problem working with Recursion in computer math, my teacher don't know how to solve it so hopefully one of you will. Here is what I have to do, it's called Cantor Dust, I give it 4 points, later to be user defined and then it draws it like this, or should at least

---------------
---- ----
- - - -
(Note spacing not right, supposed to cut it in thirds and what not)

Here is my code, note this is the first time I've used recursion. It uses CMU Graphics to draw the lines.

#include <cmugraphics.h>
#include <iostream.h>

int line(window &win,int p1,int p2,int p4,int y1,int y2);


int main()

{
window win(800,600,0,0);
int p1=50,p2=243,p4=679, // The Individual Points
y1=10,y2=10; // X and Y Points on Line
win.ChangeTitle("Cantor Dust");
win.SetPen(BLACK);

line(win,p1,p2,p4,y1,y2);

return 0;
}


int line(window &win,int p1,int p2,int p4,int y1,int y2)

{
int temp=p4;
if(p4 < p1)
return 1;
else
{
return line(win,p1,p2=p1+temp)/3,p4,y1+5,y2+5);
}
}

I'm pretty know I shouldn't increment the y values each time the function loops and should regulate it it to how much, the power of 2 to the number of rows are going down, because that yields how many lines should be drawn on that row, but can't really figure it out, hopefully one of you can help. Thanks.

Philip Nicoletti
June 6th, 2002, 09:11 AM
I am not exactly sure what your input arguments to the
line function represent.

It seems like the (non-window) arguments should be :

x1 : start x coordinate of the input line
x2 : end x coordinate of the input line
y : y value of the input line


For each input line, you need to draw two lines. So the
line function would have calls something like this :


//
length = (x2-x1)/3;
line(x1 , x1+length , y+dy); // draw first third
line(x2-length , x2 , y+dy); // draw the second third
//


Of course you need checks on when to not draw the lines
(probably length = 0).

Elrond
June 6th, 2002, 10:54 AM
int line(window &win,int p1,int p2,int p4,int y1,int y2)
{
int temp=p4;
if(p4 < p1)
return 1;
else
{
return line(win,p1,p2=p1+temp)/3,p4,y1+5,y2+5);
}
}


I don't understand a **** thing about your problem and what are your input, and outputs. But there is one thing that's pretty obvious. The condition you use to stop your recursivity is a comparison between p1 and p4, and as you never change this values from one step to the next, either the recursivity never starts if the condifion is met from the beginning (p4 < p1), or it never stops and you finish with a stack overflow error.

You should either change the value of one of them, or get a stop condition based on the parameter that is being modified: p2.

Risifo
June 6th, 2002, 12:05 PM
Oh, something must of been cut out of the source, it is

int temp=p4;

if(p4 < p1)
return 1;
else
{
win.DrawLine(p1,y1,p2,y2);
p4=p2;
return line(win,p1,p2=(p1+temp4)/3,p4,y1+5,y2+5);
}