multinomial function

double multinomial (int n, List<int> ni)

Computes the multinomial coefficient: n choose n1, n2, n3, ...

Implementation

double multinomial(int n, List<int> ni) {
  if (n < 0) {
    throw ArgumentError.value(n, 'n', messages.argumentPositive);
  }

  if (ni == null) {
    throw ArgumentError.notNull('ni');
  }

  int sum = 0;
  double ret = factorialLn(n);
  for (int i = 0; i < ni.length; i++) {
    if (ni[i] < 0) {
      throw ArgumentError.value(ni[i], 'n[${i}]', messages.argumentPositive);
    }

    ret -= factorialLn(ni[i]);
    sum += ni[i];
  }

  // Before returning, check that the sum of all elements was equal to n.
  if (sum != n) {
    throw ArgumentError.value(ni, 'ni', messages.argumentParameterSetInvalid);
  }

  return (0.5 + exp(ret)).floorToDouble();
}