CS162 Lab 9 - Pascal's Triangle

Re: CS162 Lab 9 - Pascal's Triangle

by Deleted user -
Number of replies: 0

Great question.  I bet everyone did this differently, but here's my thoughts.

Because we're using a recursive function to display the triangle, the innermost run of the function will complete first.  So I didn't bother storing the numbers, I just printed them as I went.

As an example, if my function starts out by printing 3 lines of the triangle, it looks something like:

displayTriangle(3);

Then inside my displayTriangle function, I check that number to see if it's bigger than 1.  If so, I call the function again with a smaller number, like displayTriangle(3-1);

So the function calls itself until it's only printing 1 line of the triangle.  Now I'm at the top, and can use println to display a single row of the triangle.

Once that's done, the method ends, and the rest of displayTriangle(3-1) runs, which prints out line #2 of the triangle.

Then displayTriangle(3) runs, printing line #3 of the triangle, and so on.

If I were to write it out, it would look something like:

displayTriangle(3) starts
  3 isn't 1, so call displayTriangle(3-1)
    displayTriangle(2) starts
       2 isn't 1, so call displayTriangle(2-1)
         displayTriangle(1) starts
         1 is 1, so print line 1 of the triangle
      print line 2 of the triangle
  print line 3 of the triangle

I hope that helps a little.  For me, the hardest part was figuring out how to form each line of the triangle, which I did using a math formula.  Since the assignment was more about recursion than a common and several hundred year old formula, I think it's safe to describe here.  So here goes:

Each number in a row of Pascal's Triangle can be found using it's position and the previous number in that row.  The first number of a row is always 1, I'll call this num.

Every number after the first, can be found by using num*(col-distance away from edge)/(distance away from edge)

So the 1st number in row 5 is 1.
The second number in row 5 is 1*(5-1) / 1=4.
The 2nd number in row 5 is 4 * (5-2) / 2 = 6
The 3rd number in row 5 is 6 (5-3) / 3 = 4

And so on.  This works for any row of Pascal's Triangle, and is a commonly used formula.  I'm sure there are other ways to find each number as well.

Anyway, hopefully something I said helps, post back if you're still stuck or someone has another suggestion.