
// PascalTriangle.java
// Andrew Davison, ad@coe.psu.ac.th, April 2023

/* Generate Pascal's triangle, a triangular array 
   of the binomial coefficients:

                    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
      1   7  21  35   35  21  7   1
    1   8  28  56  70   56   28  8   1

   https://en.wikipedia.org/wiki/Pascal%27s_triangle

   There is a 1 in row 0. Each entry of each subsequent row is
   constructed by adding the number above and left 
   to the number above and right, treating blank entries as 0. 
 
   Also see PascalSierpinski.java

   Usage:
     > compile PascalTriangle.java
     > run PascalTriangle <num. rows>
   e.g.
     > run PascalTriangle 14

*/

import java.math.*;
import java.util.*;

import de.tilman_neumann.jml.base.BigIntTriangle;


public class PascalTriangle
{

  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run PascalTriangle <num. rows>");
      return;
    }
    int numRows = Math.abs(Nut.parseInt(args[0]));

    BigIntTriangle tri = new BigIntTriangle(1, BigInteger.ONE); 
           // first row has index 1

    for (int n=2; n <= numRows; n++) { // using triangle indicies
      ArrayList<BigInteger> prevRow = tri.getRow(n-1);
      ArrayList<BigInteger> row = new ArrayList<>();
      for (int k=1; k <= n; k++) {  // using triangle indicies
        row.add( getEntry(prevRow, k-1).add(
                             getEntry(prevRow, k))  );
      }
      tri.addRow(row);
    }

    System.out.println("Pascal Triangle of Binomial coefs (rows 0-" +
               (numRows-1) + "):\n\n" + tri);
       // print an ASCII version of the triangle
  } /* main */


  private static BigInteger getEntry(
                     ArrayList<BigInteger> row, int i)
  {
    if ((i < 1) || (i > row.size()))  // using triangle indicies
      return BigInteger.ZERO;
    else
      return row.get(i-1);  // use ArrayList index
  } // end of getEntry()


}  // end of PascalTriangle class
