Combinations problem

Megalith

Well-known member
Joined
Aug 21, 2006
Messages
66
Programming Experience
10+
I am writing an application for doing probability. what the software essentially needs to do is to create an array with every conbination of x items picked from an array of y elements. one solution is to write a section like this

VB.NET:
Private Sub Combination(ByVal x As Integer, ByVal Array() as Integer)
Dim a, b, c, e as Integer
If x = 2 Then
e = 1 
For a = 1 To Array.GetLength - 1
for b = a + 1 To array.GetLength
Result(e,0) = Array(a)
Result(e,1) = Array(b)
e += 1
Next
Next
End If
 
If x = 3 Then
For a = 1 To Array.GetLength - 2
For b = a + 1 To Array.GetLength - 1
For c = b + 1 To Array.GetLength
Result(e,0) = Array(a)
Result(e,1) = Array(b)
Result(e,2) = Array(c)
Next
Next
Next
End If
.........
End Sub
The problem is what if x was 10 or 100 using this method i would have to write a seperate block of increasing complexity for each value of x :mad: does anyone have any suggestions for another way i can go about doing this?
 
Last edited by a moderator:
This is the sort of situation that recursion is useful for. You write a method that takes two arrays: arr1 and arr2. arr1 contains all the source objects. The method then creates a new array, arr3, that contains every combination of the elements of arr2 plus one more element from arr1. You then just call this method repeatedly until the array returned has elements of the desired length. As an example, lets' say you have the letters of the alphabet and you want every three-letter combination. You start by creating an array that contains all the one-letter combinations. Now you call your method and for every one-letter combination it will create 26 two-letter combinations, so you now have an array of 26x26 two letter combinations. You then call your method again and you now have an array of 26x26x26 three-letter combinations. You don't even necessarily have to use recursion. That's just a loop to call the method and then a loop inside the method.
 
Recursive Solutions

Sometimes you cant see the wood for the trees :) thanks for that jmcilhinney i've written a recursive algorithm that does the job perfectly and takes up hardly any code. As an added bonus it also does permutations as well saving me a lot of work i hadnt even got to yet :)
 
Back
Top