Search code examples
javarecursionbooleanpascals-triangle

Recursive method that prints Pascal's triangle upside-down and rightside-up (via boolean)


I'm trying to create a recursive method that prints the Pascal's triangle both upside-down and rightside-up. I want to use a boolean variable to switch between an upside down triangle and a rightside-up triangle. So far, I have successfully written the code to make the pascal's triangle upside down:

public class Main {
    boolean upsideDown = true;

    public void printPascal(int n) {
        if (!upsideDown) {
            //THIS IS WHERE I'M STUCK
        }
        if (upsideDown) {
            if (n < 0)
                return;
            for (int k = 0; k <= n; k++) {
                System.out.print(binom(n, k) + " ");
            }
            System.out.println();
            printPascal(n - 1);
        }
    }

    public int binom(int n, int k) {
        if (k == n || k == 0)
            return 1;
        else return binom(n - 1, k - 1) + binom(n - 1, k);
    }

    public static void main(String[] args) {
        new Main().printPascal(10); //This will print the Pascal's triangle
        //from levels 10 to 0
    }
}

So now, I'm trying to print the Pascal's triangle the rightside-up (from levels 0 to 10). How can I make a recursive method that achieves this?

I know there are lots of code online about Pascal's triangle. But I can't find anything that deals with my issue in particular.


Solution

  • It seems like the most elegant solution is to change the print order, so that the last step is printed first, followed by the second to last etc, with the first step printed last. Would this work?

    public void printPascal(int n) {
        if (!upsideDown) {
            if (n < 0)
                return;
            //print the future step first, then print current step
            printPascal(n - 1);
            System.out.println();
            for (int k = 0; k <= n; k++) {
                System.out.print(binom(n, k) + " ");
            }
        }
        if (upsideDown) {
            if (n < 0)
                return;
            for (int k = 0; k <= n; k++) {
                System.out.print(binom(n, k) + " ");
            }
            System.out.println();
            printPascal(n - 1);
        }
    }