Check combinations in an array
Hello all,
This is more of an algorithm problem than specific to VB, if anyone could point me to the correct algorithm that would suffice.
Ok, here's the problem.
I've an array, I'm not aware of its dimensions but for sure it would have only one row or one column. I have a target value and I want to find the combination and indices of the number which sum to my target value. The program can be stopped just after getting the first combination, there is no need to find all the combinations.
If any one is trying recursive function, then data type =integer can be used.
For an example, A=[8,7,3,4,5,6]
My target value = 10
Function could return indices 2 and 3 and values 7 and 3.
Thanks.
[768 byte] By [
a7n9] at [2007-11-11 7:53:28]

# 1 Re: Check combinations in an array
Try this;
Private Function Calc(Target As Integer, yourArray() as integer)
Dim Counter As Integer, I As Integer, Found As Boolean
For Counter = 0 To ubound(yourArray)-1
For I = Counter + 1 To ubound(yourArray)-1
If yourArray(Counter) + yourArray(I) = Target Then
MsgBox "The number " & Target & " was found with" & vbCrLf & vbCrLf _
& "Indices: " & Counter +1 & " and " & I+1 & vbCrLf & vbCrLf _
& "Values: " & yourArray(Counter) & " + " & yourArray(I)
Found = True
Exit For
End If
Next I
If Found = True Then Exit For
Next Counter
End Function
Steve.
# 2 Re: Check combinations in an array
Thanks Steve.
I had something similar in my mind. However, would not your code just check the combinations of two numbers only "yourArray(Counter) + yourArray(I) "
What if the Target is achieved by summing three or may be four numbers?
How to code that?
a7n9 at 2007-11-11 17:27:16 >

# 3 Re: Check combinations in an array
Hmm.. you're right, I am guilty of just coding your example.
If I get time at the weekend, I will try and think of a more elegant solution to the problem. I'll bet there is one. Also someone else may come up with a nice tidy solution.
Steve.