code: public static double chiSquare2by2(int k, int n, int r, int m) {
      int[][] cg = {{k, r - k}, {m - k, n - (k + (r - k) + (m - k))}};
      int[] cgr = {r, n - r};
      int[] cgc = {m, n - m};
      double total = 0.0;
      for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
          double exp = (double) cgr[i] * cgc[j] / n;
          total += (cg[i][j] - exp) * (cg[i][j] - exp) / exp;
        }
      }
      return total;
    }
docs: Find a 2x2 chi-square value.
  Note: could do this more neatly using simplified formula for 2x2 case.
  
  @param k The number of black balls drawn
  @param n The total number of balls
  @param r The number of black balls
  @param m The number of balls drawn
  @return The Fisher's exact p-value