Search code examples
javarecursionpascals-triangle

Pascal's Triangle Formatting


I have a program that finally works to print pascal's triangle, kind of. For whatever reason when it prints, it prints all the rows correctly as you would assume, but at the end of each row where it should just stop at one the last whole row is pasted. I'll give an example. Instead of just this:

Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
121
1331
14641

It prints this:

Enter the row number up to which Pascal's triangle has to be printed: 4
Rows to print: 4
1
11
1211
1331211
14641331211

Those extra tidbits on the end are not supposed to be there. I have no idea why there are there. Any help is much appreciated.

"Yes, it is supposed to use recursion, and no, I can't change that."

Here is my code:

import java.util.Scanner;

public class pascalsTriangle {
    public static int rows;
    public static String list = "";
    public static String line = "1";

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter the row number up to which Pascal's triangle has to be printed: ");
        rows = scan.nextInt();
        System.out.println("Rows to print: " + rows);
        scan.close();
        if (rows == 1)
            System.out.println("1");
        else {
            System.out.println(print(1, rows));
        }
    }

    public static String print(int largest, int row) {
        if (row < 1)
            return "1";
        else{
            list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
        }
        return list;
    }

    public static String curLine(int n, int k, int last) {
        if(n > k && n != 0){
            line = Integer.toString(last) + curLine(n, k + 1, last*(n - k)/(k + 1));
        }
        return line;
    }
}

Solution

  • When your program moves to put together the next line of the triangle, your String variable line needs to be reset back to just "1". What's happening is that when your program moves to the next line, line is still the previous line of numbers, and it adds the triangle onto that. Notice how the "extra tidbit" on the last line: 14641'331211' matches up with the row above it: 1'331211'

    Alternatively you could work-around this using a substring by changing your line:

    list = print(1, row - 1) + "\n" + curLine(row, 0, 1);
    

    To:

    list = print(1, row - 1) + "\n" + curLine(row, 0, 1).substring(0,row+1);
    

    And that will solve your problem entirely