Combinations Sub: choose(n,k)

Stellaferox

Active Member
Licensed User
Hi,

I developed a sub for computinf the amout of combinations, given a population N, choose subset K (notation: choose(n,k).
Example: how many combinations are possible for 7 cards from 52?
choose(52,7). To compute n!/((n-k)!*k!)
Because this creates an overflow for relatively small numbers I created an alternative and really fast routine.

B4X:
Sub Choose(nn,kk)
   ' effficient Choose method implementation

   If (nn<0) OR (kk<0) Then Msgbox("Invalid negative parameter in Choose()..")
   If (nn<kk) Then Return 0
   If (nn=kk) Then Return 1

   delta = 0
   imax = 0

   If (kk < (nn-kk)) Then 'choose(100,3)
      delta = nn-kk
      imax = kk
   Else 'choose(100,97)
      delta = kk
      imax = nn-kk
   End If

   ans = delta+1
   For i = 2 To imax
      ans = (ans * (delta + i))/i
   Next
   Return ans
End Sub
I am building an application for displaying and storing all possible combinations. When ready I will publish.

Have fun

Marc
 
Top