# Pascal's Triangle formatting.

• 02-19-2010, 02:54 AM
dalangley
Pascal's Triangle formatting.
Hey there everyone :). I am having a bit of trouble with a recursive program I am working on involving Pascals triangle. I have written the method to print the triangle but I am getting the wrong format as far as the output goes.

Here is the method: (Is this recursive ?)

Code:

```public static int [] ptriangle(int r)     {     if (r == 0)     {         int [] last = new int[1];         last[0] = 1;         return last;     }     int [] nextNum = new int[r+1];     int [] numAbove = ptriangle(r-1);     System.out.println(" ");     for (int i = 0; i < r; i++)     {         System.out.print(" ");             if (i == 0)             {                 nextNum[i] = 1;             }                 else if(i == r)                     {                         nextNum[i] = 0;                     }                     else                         {                             nextNum[i] = numAbove[i-1] + numAbove[i];                         }                             System.out.print(nextNum[i] + " ");     }     return nextNum;     }```
Output with above method:

Code:

```  1   1  1   1  2  1   1  3  3  1   1  4  6  4  1   1  5  10  10  5  1   1  6  15  20  15  6  1 [B][I@addbf1[/B] < - Where is this coming from?```
So my questions are, is this method recursive? And where do i need to input a println() or print() statement in order to get the appropriate format? Also where is that jumbled mess coming out at the end from?
• 02-19-2010, 03:11 AM
travishein
 my bad,, This is a recursive method, a recursive method is one that would invoke itself such as from within itself.

I'm trying to thing this out myself. I think we would want to define a maximum width of printing, and for every row, would left pad the string with half of the spaces minus half of the length of the numbers being printed (and the same for right padding it, if we wanted to see characters after the triangle, but here probably just spaces, which we can omit and just use end of line.
• 02-19-2010, 03:15 AM
dalangley
Quote:

Originally Posted by travishein
 my bad,, This is a recursive method, a recursive method is one that would invoke itself such as from within itself.

I'm trying to thing this out myself. I think we would want to define a maximum width of printing, and for every row, would left pad the string with half of the spaces minus half of the length of the numbers being printed (and the same for right padding it, if we wanted to see characters after the triangle, but here probably just spaces, which we can omit and just use end of line.

My two main concerns is getting it formatted into the pyramid shape and getting rid of that jumbled mess at the end, not sure whats causing that.
• 02-19-2010, 03:17 AM
travishein
I'm not sure how you're getting that funny [I@addbf1 though. I ran this with ptriangle(7); and i don't get that. Though this looks like the java notation for an array of int[] . Like if I did
Code:

`System.out.println(new int[]{});`
it would print that.
• 02-19-2010, 03:20 AM
travishein
i bet in your main you were doing
Code:

`System.out.println(ptriangle(7));`
• 02-19-2010, 03:24 AM
dalangley
Quote:

Originally Posted by travishein
I'm not sure how you're getting that funny [I@addbf1 though. I ran this with ptriangle(7); and i don't get that. Though this looks like the java notation for an array of int[] . Like if I did
Code:

`System.out.println(new int[]{});`
it would print that.

Also do you have any insight on where I need to insert a new line into the method itself to form the familiar pyramid shape?

Code:

```public class PascalTriTest {     /**     * @param args the command line arguments     */     public static void main(String[] args) {     PascalTri.ptriangle(7); }```
EDIT: You were right, I have gotten rid of the jumbled mess, I figured out it was like telling something to call itself twice ? No need for the println() method as it already prints in the method itself.

Now for the pyramid, anythoughts?
• 02-19-2010, 03:33 AM
dalangley
No ideas on the pyramid formatting?
• 02-19-2010, 03:39 AM
travishein
See line 30,
Code:

```// compute padding before the line, (padding width) * (#items this line / 2)     int padding = 4 * (startRow -thisRow) / 2;     padString(outputBuffer, padding, " ");```
Thats kind of what i was thinking it should do in my word-dy description above.

Code:

```/**  *Created on Feb 18, 2010  */ /**  * Sample pascal triangle formatting for the forum.  * @author thein  */ public class PascalsTriangle {   /**   * Starts computing with the bottom row and computes recursively up to the top row.   * Where the output of the triangle is rendered out from top to bottom.   * @param outputBuffer what we build the output into, to later be printed out.   * @param startRow the original start row number, goes along for the ride, used to compute paddings to align the triangle   * @param thisRow the current row number to compute   * @return the values to be used on the previous row.   */   private static int[] ptriangle(StringBuilder outputBuffer, int startRow, int thisRow) {     if (thisRow == 0) {       // terminal case       int[] last = new int[1];       last[0] = 1;       return last;     }     int[] nextNum = new int[thisRow + 1];     int[] numAbove = ptriangle(outputBuffer, startRow, thisRow - 1);         // compute padding before the line, (padding width) * (#items this line / 2)     int padding = 4 * (startRow -thisRow) / 2;     padString(outputBuffer, padding, " ");       for (int i = 0; i < thisRow; i++) {       if (i == 0) {         nextNum[i] = 1;       }       else if (i == thisRow) {         nextNum[i] = 0;       }       else {         nextNum[i] = numAbove[i - 1] + numAbove[i];       }             // right pad the number to 2 decimal places       String number = String.valueOf(nextNum[i]);             padString(outputBuffer, (3 - number.length()), " ");       outputBuffer.append(number).append(" ");     } // for     outputBuffer.append("\n");     return nextNum;   }   /**   * pads a string builder with a specified character a given number of times.   * @param b   * @param padding   * @param character   */   public static void padString(StringBuilder b, int padding, String character) {     for (int i = 0; i < padding; i++) {       b.append(character);     }     }     /**   * Convenience wrapper method to initially invoke the recursive method   * @param outputBuffer   * @param startRow   */   public static void ptriangle(StringBuilder outputBuffer, int startRow) {     ptriangle(outputBuffer, startRow, startRow);   }   private static void usage() {     System.err.println("Usage: PascalsTriangle <depth>");     System.exit(1);     }     /**   * Generates a pascal's triangle to the specified depth.   * @param args   */   public static void main(String[] args) {     if (args.length != 1) {       usage();     }         String strLine = args[0];     int lines = 0;     try {       lines = Integer.parseInt(strLine);     }     catch (NumberFormatException ex) {       System.err.println("invalid number: " + strLine);       usage();     }         if (lines < 1) {       System.err.println("lines must be a number greater than 1.");       usage();     }         StringBuilder outputBuffer = new StringBuilder();     ptriangle(outputBuffer, lines);     System.out.println(outputBuffer.toString());   } }```
See, pretty triangle.
Code:

```java PascalsTriangle 7               1             1  1           1  2  1         1  3  3  1       1  4  6  4  1     1  5  10  10  5  1   1  6  15  20  15  6  1```
• 02-19-2010, 03:42 AM
travishein
Though I guess you could have just kept using the System.out.print() for the padding and printing the numbers. The other trick i used was to pass in the starting row number and pass it along for the ride, so that we can compute the amount of padding needed for each row, if the triangle was always supposed to be a fixed size then I guess this wouldn't be needed either.
• 02-19-2010, 03:54 AM
dalangley
Quote:

Originally Posted by travishein
Though I guess you could have just kept using the System.out.print() for the padding and printing the numbers. The other trick i used was to pass in the starting row number and pass it along for the ride, so that we can compute the amount of padding needed for each row, if the triangle was always supposed to be a fixed size then I guess this wouldn't be needed either.

I followed your code and it seems like it would work, but I really think the solution can be found without drastically changing what I had, if you look back at my method to me it seems like inserting a line inside of one of the for loops or creating another for loop involving what row it is currently on then it would be an easy solution.

I say this but I cannot wrap my head around where or what type of statement I need to insert.

Any ideas looking back at my method?

EDIT: How would you do it with the System.out.println methods, (that is what im looking for, we dont use buffers in this course, at least not yet), while incorporating the row number?
• 02-19-2010, 04:09 AM
travishein
Right, thats what I was saying after I posted it. Kind of went to town on it.

Well, if you assume its always level 7, I guess you don't need to pass in the original starting rows parameter. Its not as elegant that way, but is simpler.

so then

Code:

```    int [] nextNum = new int[r+1];     int [] numAbove = ptriangle(r-1);     // System.out.println(" ");     // compute padding before the line, (padding width) * (#items this line / 2)     int startRow = 7;     int padding = 4 * (startRow - thisRow) / 2;     for (int i = 0; i < padding; i++) {       System.out.print(" ");     }     // existing code     for (int i = 0; i < r; i++)     {```
and after the for() loop, you need to add a system.out.println() right

Code:

```} System.out.println();     return nextNum;```
• 02-19-2010, 04:18 AM
dalangley
Quote:

Originally Posted by travishein
Right, thats what I was saying after I posted it. Kind of went to town on it.

Well, if you assume its always level 7, I guess you don't need to pass in the original starting rows parameter. Its not as elegant that way, but is simpler.

so then

Code:

```    int [] nextNum = new int[r+1];     int [] numAbove = ptriangle(r-1);     // System.out.println(" ");     // compute padding before the line, (padding width) * (#items this line / 2)     int startRow = 7;     int padding = 4 * (startRow - thisRow) / 2;     for (int i = 0; i < padding; i++) {       System.out.print(" ");     }     // existing code     for (int i = 0; i < r; i++)     {```
and after the for() loop, you need to add a system.out.println() right

Code:

```} System.out.println();     return nextNum;```

I see what your saying, your comment slashes confuse me a bit as I can see where you want me to place it, but not exactly, do i place this entire segment:

Code:

```System.out.println(" ");     // compute padding before the line, (padding width) * (#items this line / 2)     int startRow = 7;     int padding = 4 * (startRow - thisRow) / 2;     for (int i = 0; i < padding; i++) {       System.out.print(" ");```
between this segment:

Code:

```int [] nextNum = new int[r+1];//Holds next numbers in the sequence.     int [] numAbove = ptriangle(r-1);//Grabs the numbers in the line above.```
and this segment?:
Code:

```System.out.println(" ");     for (int i = 0; i < r; i++)     {         System.out.print(" ");             if (i == 0)// Base case.             {                 nextNum[i] = 1;             }```
• 02-19-2010, 05:47 AM
travishein
ah sorry. yea, its kind of hard to show the differences of existing code and added code in this posting tool, like there should be a highlight or bold the added / changed lines. feature. Oh there is if I get out of quick edit..

ok so here is the full code with the changes to make it do the triangle printing highlighted in their place

Code:

```  public static int [] ptriangle(int r)   {     if (r == 0)     {       int [] last = new int[1];       last[0] = 1;       return last;     }       int [] nextNum = new int[r+1];     int [] numAbove = ptriangle(r-1);       [B] int startRow = 7;     int padding = 4 * (startRow - r) / 2;         for (int i = 0; i < padding; i++)     {       System.out.print(" ");     }[/B]         for (int i = 0; i < r; i++)     {       System.out.print(" ");       if (i == 0)       {         nextNum[i] = 1;       }       else if(i == r)       {         nextNum[i] = 0;       }       else       {         nextNum[i] = numAbove[i-1] + numAbove[i];       }             [B]String strNum = String.valueOf(nextNum[i]);       for (int j = strNum.length(); j < 2; j++) {         System.out.print(" ");       }       System.out.print(strNum + " ");[/B]     } [B]    System.out.println();[/B]     return nextNum;   }```
• 02-19-2010, 09:10 AM
JosAH
Quote:

Originally Posted by dalangley
Output with above method:

Code:

```  1   1  1   1  2  1   1  3  3  1   1  4  6  4  1   1  5  10  10  5  1   1  6  15  20  15  6  1 [B][I@addbf1[/B] < - Where is this coming from?```

You're not showing us all of your code; there's a System.out.println( ... ) statement in there that tries to print an entire int array.

kind regards,

Jos