23

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.

niczky12
  • 4,953
  • 1
  • 24
  • 34
rodrigolece
  • 1,039
  • 2
  • 13
  • 19

2 Answers2

33

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]
Julia Learner
  • 2,754
  • 15
  • 35
niczky12
  • 4,953
  • 1
  • 24
  • 34
5

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
Steven Siew
  • 843
  • 8
  • 11
  • 2
    `julia> binomial(big"300", 200) 4158251463258564744783383526326405580280466005743648708663033657304756328324008620` also works. – Julia Learner Sep 21 '18 at 23:00