01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package algs11;
import stdlib.*;
/* ***********************************************************************
 *  Compilation:  javac Binomial.java
 *  Execution:    java Binomial N k p
 *  Dependencies: StdOut.java
 *
 *  Reads in N, k, and p as command-line arguments and prints out
 *  (N choose k) p^k (1-p)^N-k.
 *
 *  % java Binomial 5 2 .25
 *  0.263671875
 *  0.263671875
 *
 *  % java Binomial 5 3 .25
 *  0.087890625
 *  0.087890625
 *
 *  % java Binomial 5 0 .25
 *  0.2373046875
 *  0.2373046875
 *
 *  % java Binomial 5 5 .25
 *  9.765625E-4
 *  9.765625E-4
 *
 *************************************************************************/

public class XBinomial {

  // slow
  public static double binomial1(int N, int k, double p) {
    if (N == 0 && k == 0) return 1.0;
    if (N < 0 || k < 0) return 0.0;
    return (1.0 - p) *binomial1(N-1, k, p) + p*binomial1(N-1, k-1, p);
  }

  // memoization
  public static double binomial2(int N, int k, double p) {
    double[][] b = new double[N+1][k+1];

    // base cases
    for (int i = 0; i <= N; i++)
      b[i][0] = Math.pow(1.0 - p, i);
    b[0][0] = 1.0;

    // recursive formula
    for (int i = 1; i <= N; i++) {
      for (int j = 1; j <= k; j++) {
        b[i][j] = p * b[i-1][j-1] + (1.0 - p) *b[i-1][j];
      }
    }
    return b[N][k];
  }

  public static void main(String[] args) {
    args = new String[] { "5", "2", ".25" };
    //args = new String[] { "5", "3", ".25" };
    //args = new String[] { "5", "0", ".25" };
    //args = new String[] { "5", "5", ".25" };

    int N = Integer.parseInt(args[0]);
    int k = Integer.parseInt(args[1]);
    double p = Double.parseDouble(args[2]);
    StdOut.println(binomial1(N, k, p));
    StdOut.println(binomial2(N, k, p));
  }

}