What is the Julia function to count combinations (n choose k)?

rodrigolece picture rodrigolece · Apr 30, 2018 · Viewed 7.6k times · Source

I'm looking for the (hopefully built-in) function in Julia that calculates the number of combinations

nChooseK

I could obviously implement my own using factorials, but I'm almost certain somebody has already worried about this.

Answer

niczky12 picture niczky12 · Apr 30, 2018

Chances are you're looking for the binomial function that returns the binomial coefficient. It's currently in base

Here are some simple examples:

julia> binomial(2,1)
2

julia> binomial(3,2)
3

If you want to see the actual combinations, then you can use the Combinatorics package's combinations(a,n) function. This gives you an iterable with all the possible combinations of length n of array a.

julia> using Combinatorics

julia> collect(combinations(1:3,2))
3-element Array{Array{Int64,1},1}:
 [1, 2]
 [1, 3]
 [2, 3]