It's not clear to me in what form you want your VB code to return the combinations it generates, but for simplicity let's assume a list of lists. VB does allow recursion, and a recursive solution is simplest. Doing combinations rather than permutations can be obtained easily, by simply respecting the ordering of the input list.
So, the combinations of K items out of a list L that's N items long are:
- none, if K > N
- the whole list L, if K == N
- if K < N, then the union of two bunches: those that contain the first item of L and any of the combinations of K-1 of the other N-1 items; plus, the combinations of K of the other N-1 items.
In pseudocode (using for example .size to give a list's length, [] as an empty list, .append to add an item to a list, .head to get a list's first item, .tail to get the list of "all but the first" items of L):
function combinations(K, L):
if K > L.size: return []
else if K == L.size:
result = []
result.append L
return result
else:
result = []
for each sublist in combinations(K-1, L.tail):
subresult = []
subresult.append L.head
for each item in sublist:
subresult.append item
result.append subresult
for each sublist in combinations(K, L.tail):
result.append sublist
return result
This pseudocode can be made more concise if you assume more flexible list-manipulation syntax. For example, in Python ("executable pseudocode") using "slicing" and "list comprehension" syntax:
def combinations(K, L):
if K > len(L): return []
elif K == len(L): return [L]
else: return [L[:1] + s for s in combinations(K-1, L[1:])
] + combinations(K, L[1:])
Whether you need to verbosely construct lists by repeated .append, or can concisely construct them by list comprehension notation, is a syntax detail (as is the choice of head and tail vs list slicing notation to get the first item of the list vs the rest): the pseudocode is intended to express exactly the same idea (which is also the same idea expressed in English in the previous numbered list). You can implement the idea in any language that is capable of recursion (and, of course, some minimal list operations!-).