Ben Chuanlong Du's Blog

It is never too late to learn.

Hands on the CombinatoricsUtils class in Apache Commons Math

In [3]:
%%classpath add mvn
org.apache.commons commons-math3 3.6.1
In [4]:
import org.apache.commons.math3.util.CombinatoricsUtils._
Out[4]:
import org.apache.commons.math3.util.CombinatoricsUtils._

binomialCoefficient

In [5]:
binomialCoefficient(5, 3)
Out[5]:
10
In [6]:
binomialCoefficientDouble(5, 3)
Out[6]:
10.0
In [7]:
binomialCoefficientLog(5, 3)
Out[7]:
2.302585092994046
In [8]:
checkBinomial(5, 3)

combinationsIterator

Notice that this methods returns an iterator of the type java.util.Iterator[Array[Int]], which is not a Scala Iterator! For combinations/permutations iterator, it is suggested that you use Seq.combinations and/or Seq.permutations.

In [10]:
val it = combinationsIterator(5, 3)
Out[10]:
org.apache.commons.math3.util.Combinations$LexicographicIterator@1ab48026

Factorial

In [11]:
factorial(10)
Out[11]:
3628800
In [14]:
factorial(100)
org.apache.commons.math3.exception.MathArithmeticException: arithmetic exception
  at org.apache.commons.math3.util.CombinatoricsUtils.factorial(CombinatoricsUtils.java:281)
  ... 46 elided
In [15]:
factorialDouble(100)
Out[15]:
9.332621544395286E157
In [16]:
factorialDouble(20)
Out[16]:
2.43290200817664E18
In [17]:
factorialLog(100)
Out[17]:
363.7393755555636

Stirling

In [18]:
stirlingS2(10, 3)
Out[18]:
9330
In [ ]:

Comments