' Collection of code snippets by Arne Vajhøj 
' (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
Function Fac(n As Integer) As Long
    If n > 1 Then
        Fac = n * Fac(n - 1)
    Else
        Fac = 1
    End If
End Function

Sub Combi2Help(posleft As Integer, y() As Integer, start As Integer, res() As Integer, ix As Integer, tmp() As Integer)
    Dim i, j As Integer
    For i = start To UBound(y) - posleft
        tmp(UBound(tmp) - posleft) = y(i)
        If posleft > 1 Then
            Call Combi2Help(posleft - 1, y, i + 1, res, ix, tmp)
        Else
            For j = LBound(tmp) To UBound(tmp)
                res(ix, j) = tmp(j)
            Next
            ix = ix + 1
        End If
    Next
End Sub

Function Combi2(x As Integer, y() As Integer) As Integer()
    Dim res() As Integer
    Dim tmp() As Integer
    ReDim res(Fac(UBound(y) - LBound(y) + 1) \ (Fac(UBound(y) - LBound(y) + 1 - x) * Fac(x)), x)
    ReDim tmp(x)
    Call Combi2Help(x, y, LBound(y), res, 0, tmp)
    Combi2 = res
End Function

Function TestCombi2()
    Dim i As Integer
    Dim vals(5) As Integer
    Dim res() As Integer
    Dim resstr As String
    vals(0) = 1
    vals(1) = 2
    vals(2) = 3
    vals(3) = 4
    vals(4) = 5
    res = Combi2(3, vals)
    resstr = ""
    For i = 0 To 9
        resstr = resstr & "(" & res(i, 0) & "," & res(i, 1) & "," & res(i, 2) & ")"
    Next
    MsgBox (resstr)
End Function
