2

My teacher wrote us a tester class for his problem with Pascal's triangle. Here it is:

public class TestTriangle {
    public static void main(String args[]) {
        PascalsTriangle triangle = new PascalsTriangle(7);
        if (triangle.getElement(5, 2) == 10)
            System.out.println("Triangle has passed one test.");
        else
            System.out.println("Triangle is wrong.");
        triangle.showTriangle();
    }
}

Here is my code:

public class PascalsTriangle {
    private int rows;
    private int column;
    private int position;

    /**
     * Constructor for objects of class PascalsTriangle
     */
    public PascalsTriangle() {
        rows = 2;
    }

    public PascalsTriangle(int n) {
        rows = n;
    }

    public int getElement(int n, int k) {
        rows = n;
        column = k;
        //now the equation
        int z;
        int y;
        int d;
        for (z = 1; z <= n; z++) { //z is n! at nominator of equation
            int a = z;
            z = z * n;
            z = a + z;
        }
        for (y = 1; y <= k; y++) { //y is k! at denominator of equation
            int b = y;
            y = y * k;
            y = b + y;
        }
        int c = n - k;
        for (d = 1; d <= c; d++) { //d is (n-k)! at denominator of equation
            int e = d;
            d = d * c;
            d = e + d;
        }
        position = z / (y * d);
        return position;
    }

    public showTriangle() { //outputs entire triangle
    }
}

The only issue I have is with the showTriangle method. I don't know how to make it output the entire triangle. How would I print out the entire triangle if the only formula I have is for finding a specific position?

Community
  • 1
  • 1
Erika
  • 31
  • 2

1 Answers1

0

I compiled your code. Java forced me to declare a return type for showTriangle(). I chose void:

public void showTriangle() 
{
}

I ran the test

triangle.getElement(5,2)==10

And the program printed

Triangle is wrong.

Are you sure the the getElement method returns the right result? I printed the result of getElement(5,2) and got0.

Once the getElement function is working, I would implement the showTriangle() method with two loops. In pseudo-code, it would look like this. One loop for the row number (n) and one loop for the column(k)

for i = 0 to n
{
    for j = 0 to k
    {
        System.out.print(getElement(i,j) + " ") //Print triangle value and a space
    }
    System.out.print("\n") //Skip down one line
}
//NOTE: You have to pick the right value of k based on the n.

This won't print a beautifully formatted triangle, but if getElement() works correctly, should print something:

1 
1 1 
1 2 1 
ahoffer
  • 6,347
  • 4
  • 39
  • 68