I have thought about this issue a lot, and I have found a way to do it, but there has to be a better way. I want to enter a target number, then loop through an array and find any possible combination of numbers that adds up to equal that target number.
For example, I know this code works to find all combinations of two numbers that add up to equal the target number:
For i as Integer = 0 To MyArray.Length - 1
For j as Integer = (i + 1) To MyArray.Length - 1
If(MyArray(i) + MyArray(j)) = TargetNumber Then
'Output these two numbers
EndIf
Next
Next
As you can see, this algorithm is designed only to get combinations of two numbers that add up to equal the target number. I know that I could nest another For
loop (or as many as I want) to find as many numbers as I want to find, but there has to be a better, more efficient way. I don't want to have to nest another loop every time I want to find another number. Any suggestions? Should I avoid using arrays and try some other approach? Any help is appreciated.