Question

Ok so I'm trying to create a recursive algorithm which results in series of circles being produced.

At present it can be seen that I have created the circle class and attempted to use recursion, however as you can probably tell I'm fairly new to all this.

Having now drawn all of the ovals in their correct locations I have included a Color object into each circle. My aim is to make it so that as the circles are produced their colors change, with each set of circles being a certain shade of green (as seen in the above example).

Presently, however the shades of green are applied to the incorrect circles. As is seen below:

If anyone is able to hazard a guess as to why this is happening I would be very grateful. Thanks.

Was it helpful?

Solution

Every call to createCircles() should paint one large circle in the center and call itself recursively 3 times for the 3 smaller circles. The y coordinate always remains the same and you can recalculate the x coordinate by adding and subtracting the radius of original circle.

public void createCircles(int x, int y, int rad) {

    Circle myCircle = new Circle(x, y, rad);
    circles.add(myCircle);

    createCircles(x - (2*rad), y, rad/3);
    createCircles(x, y, rad/3);
    createCircles(x + (2*rad), y, rad/3);
}

For the overflow error you can set a terminating condition on the size of rad, like

if (rad < 5) {
    return;
}

OTHER TIPS

You need a base case. That is like an exit method for recursion. In your case, the createCircles method repeats infinitely, that is why it gives an overflow exception. Try this.

public void createCircles(int x, int y, int rad){

    int myX = x/3;
    int myRad = rad/3;

    if(rad != 0){
       Circle myCircle = new Circle(myX, y, myRad);
       circles.add(myCircle);
       createCircles(myX, y, myRad);
       createCircles(myX, y, myRad);
       createCircles(myX, y, myRad);
    }
}

Exit clause: If circle radius becomes too small to be worth painting.

I appreciate that at the moment I'm getting an overflow error because I haven't got an exit clause for the recursion.

Recursive algorithms do, indeed, need a termination condition.

In your case you do not want to keep recursing once the circle are small enough. So basically you'd simply wrap the three recursive calls you have here:

    createCircles(myX, y, myRad);
    createCircles(myX, y, myRad);
    createCircles(myX, y, myRad);

Into something like this (untested but it should get your started):

    if (myRad > 0) {
        createCircles(myX, y, myRad);
        createCircles(myX, y, myRad);
        createCircles(myX, y, myRad);
    }

Because it makes no sense to keep drawing circle with a radius of zero.

Here's a Wikipedia entry about termination condition:

http://en.wikipedia.org/wiki/Recursion_termination

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top