Combinations Sub: choose(n,k)

Discussion in 'Code Samples & Tips' started by Stellaferox, Feb 21, 2008.

  1. Stellaferox

    Stellaferox Active Member Licensed User


    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.

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

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

       delta = 
       imax = 

    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+
    For i = 2 To imax
          ans = (ans * (delta + i))/i
    Return ans
    End Sub
    I am building an application for displaying and storing all possible combinations. When ready I will publish.

    Have fun

  2. derez

    derez Expert Licensed User

  3. Stellaferox

    Stellaferox Active Member Licensed User

    Hi David,

    Yes I have and I find it very useful.
    Thank you for that, by the way...
    However I needed an application for my main application to find a next combination without using recursive programming.
    I found it at:
    I translated the code a bit and added some for my own code. Now I can use any combination and find its immediate successor or predecessor.
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice