I'm looking for the (hopefully built-in) function in Julia that calculates the number of combinations
I could obviously implement my own using factorials, but I'm almost certain somebody has already worried about this.
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.
and we choose r of them, no repetition, order doesn't matter. It is often called "n choose r" (such as "16 choose 3")
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With