Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 689
rodrigolece Avatar asked Apr 30 '18 13:04

rodrigolece


People also ask

What is n choose k equal to?

N choose K is called so because there is (n/k) number of ways to choose k elements, irrespective of their order from a set of n elements. To calculate the number of happenings of an event, N chooses K tool is used. This is also called the binomial coefficient.

What does n Choose R mean?

and we choose r of them, no repetition, order doesn't matter. It is often called "n choose r" (such as "16 choose 3")


2 Answers

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]
like image 96
niczky12 Avatar answered Sep 18 '22 20:09

niczky12


Be aware to use BigInt if you want to take binomial of "big" numbers like 200

julia> binomial(3,2)
3

julia> binomial(300,200)
ERROR: OverflowError: binomial(300, 200) overflows
Stacktrace:
 [1] binomial(::Int64, ::Int64) at ./intfuncs.jl:876
 [2] top-level scope at none:0

julia> binomial(BigInt(300),BigInt(200))
4158251463258564744783383526326405580280466005743648708663033657304756328324008620
like image 44
Steven Siew Avatar answered Sep 20 '22 20:09

Steven Siew