BinomialCoefficients.java


Below is the syntax highlighted version of BinomialCoefficients.java from §1.4 Arrays.


/******************************************************************************
 *  Compilation:  javac BinomialCoefficients.java
 *  Execution:    java BinomialCoefficients n
 *
 *  Prints out binomial coefficients such that such that a[n][k] contains
 *  the probability that you get exactly k heads when you toss a
 *  coin n times.
 *
 *  See also https://introcs.cs.princeton.edu/java/14array/BinomialDistribution.java
 *
 *  % java BinomialCoefficients 7
 *  1/1
 *  1/2 1/2
 *  1/4 2/4 1/4
 *  1/8 3/8 3/8 1/8
 *  1/16 4/16 6/16 4/16 1/16
 *  1/32 5/32 10/32 10/32 5/32 1/32
 *  1/64 6/64 15/64 20/64 15/64 6/64 1/64
 *
 ******************************************************************************/

public class BinomialCoefficients {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);

        int[][] pascal = new int[n+1][];

        // initialize first row
        pascal[1] = new int[1 + 2];
        pascal[1][1] = 1;

        // fill in Pascal's triangle
        for (int i = 2; i <= n; i++) {
            pascal[i] = new int[i+2];
            for (int k = 1; k < pascal[i].length - 1; k++)
                pascal[i][k] = pascal[i-1][k-1] + pascal[i-1][k];
        }

        // print binomial coefficients
        int denominator = 1;
        for (int i = 1; i <= n; i++) {
            for (int k = 1; k < pascal[i].length - 1; k++) {
                System.out.print(pascal[i][k] + "/" + denominator + " ");
            }
            System.out.println();
            denominator += denominator;
        }
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:13:44 EDT 2022.