how to make possible combinations of numbers

seco

Well-known member
Joined
Mar 4, 2007
Messages
66
Programming Experience
Beginner
Hi
i have an array like this

groupid number
1 235
2 987
3 781
4 879
and so on .....

and i want to make a combination of groups that has sum between say 1000 and 1500 or what ever.

how to iterate through all possible combinations of all items (i mean if i have 10 groups it will be 10 power 10 combinations right?) so how to do that?

thanks in advance.
 
Assuming order isnt important, and if you do it right, it wont be an exponential number of rows.

If we can say that Element1+Element2 is the same as Element2+Element1, you cut the iterations dramatically.

A quick rough pass at this yields:

VB.NET:
Module Module1

    Sub Main()

        Dim myNumbers As New List(Of Integer)
        myNumbers.Add(255)
        myNumbers.Add(700)
        myNumbers.Add(685)
        myNumbers.Add(157)
        myNumbers.Add(238)



        For currentNumberIndex As Integer = 0 To myNumbers.Count - 1
            For currentPartnerIndex As Integer = currentNumberIndex + 1 To myNumbers.Count - 1
                If ((myNumbers(currentNumberIndex) + myNumbers(currentPartnerIndex) > 1000) And _
                    (myNumbers(currentNumberIndex) + myNumbers(currentPartnerIndex) < 1500)) Then

                    Console.WriteLine("Match found: " & myNumbers(currentNumberIndex) & " + " & myNumbers(currentPartnerIndex) & " = " & _
                        (myNumbers(currentNumberIndex) + myNumbers(currentPartnerIndex)))
                Else
                    Console.WriteLine("No Match: " & myNumbers(currentNumberIndex) & " + " & myNumbers(currentPartnerIndex) & " = " & _
                        (myNumbers(currentNumberIndex) + myNumbers(currentPartnerIndex)))
                End If
            Next
        Next
        Console.ReadKey()
    End Sub

End Module

Outputs:
VB.NET:
No Match: 255 + 700 = 955
No Match: 255 + 685 = 940
No Match: 255 + 157 = 412
No Match: 255 + 238 = 493
Match found: 700 + 685 = 1385
No Match: 700 + 157 = 857
No Match: 700 + 238 = 938
No Match: 685 + 157 = 842
No Match: 685 + 238 = 923
No Match: 157 + 238 = 395

Which I am sure could be cleaned up, but I didn't look at it for to long...
 
thanks for reply
you just make the combination between every 2 elements for adding and i have thousands of elements and i want to get all possible combinations. not just between every 2 elements but any number of the array with any number

if i have 4 elements it will be:
1+2
1+3
1+4
2+3
2+4
1+2+3
1+2+4
and so on....
 
Back
Top