Kynian
Kynian

Reputation: 670

Trying to create an Htree using Recursion in Java, unable to get it to do more than one corner

I'm currently taking a class in Java and our professor is having us write a program using recursion to build an "Htree" which is just an H with smaller H's on every corner of the first, and down as many levels as the user specifies. So far I have it recursively creating the FIRST corner, but I can't seem to figure out how to change it so it will do all four corners. Here is my code:

package assignment3;

public class Htree {

    public static void main(String[] args) {

        int SIZE = 512;

        // Output and entry take place in the console window

        Turtle.create(SIZE, SIZE);

        int xCenter = SIZE / 2;
        int yCenter = SIZE / 2;

        int x = 4;
        recursive(xCenter, yCenter, x);
    }

    private static void recursive(int xCenter, int yCenter, int x) {
        int x2 = x - 1;

        if (x2 < 0) {
            return;
        }
        int left = xCenter - xCenter / 2;
        int right = xCenter + xCenter / 2;
        int top = yCenter - yCenter / 2;
        int bottom = yCenter + yCenter / 2;
        int middle = yCenter;

        Turtle.fly(right, middle);
        Turtle.go(left, middle);
        Turtle.fly(right, top);
        Turtle.go(right, bottom);
        Turtle.fly(left, top);
        Turtle.go(left, bottom);
        recursive(left, top, x2);

        System.out.println("Done");
    }
}

And it's supposed to look something like this: Htree

Any tips would be appreciated.

Upvotes: 2

Views: 2594

Answers (1)

James Waldby - jwpat7
James Waldby - jwpat7

Reputation: 8711

Your code like

    int left = xCenter - xCenter / 2;
    int right = xCenter + xCenter / 2;

is problematic. Suppose the X centers for second-level H's should be at x=2 and x=6. For the lefthand H you compute left=1, right=3, so it would be 2 units wide. But for the righthand H you compute left=3, right=9, so it is 6 units wide. Conclusion: your recursive routine needs another parameter, to specify width, and you would use formulas like left=xCenter-wide/2, right=xCenter+wide/2.

Here is pseudocode for an easy way to do the four different recursive calls (with drawH(xCenter, yCenter, wide, deep) used in place of your recursive(left, top, x2); function):

p = q = 1
for i in {1..4}:
    drawH(xCenter+p*size/xratio, yCenter+q*size/yratio, wide/2, deep-1)
    q = p*q; p = -p; 

Correction and note, May 2016: The last line of pseudocode, q = p*q; p = -p;, produces (p, q) pairs {(1, 1), (-1, 1), (1, -1), (-1, -1)} for the four bars of the H.

Upvotes: 3

Related Questions