I'm trying to take the first block of code from this link: http://www.geeksforgeeks.org/dynamic-programming-subset-sum-problem/ Copied and pasted below:
bool isSubsetSum(int set[], int n, int sum)
{
// Base Cases
if (sum == 0)
return true;
if (n == 0 && sum != 0)
return false;
// If last element is greater than sum, then ignore it
if (set[n-1] > sum)
return isSubsetSum(set, n-1, sum);
/* else, check if sum can be obtained by any of the following
(a) including the last element
(b) excluding the last element */
return isSubsetSum(set, n-1, sum) || isSubsetSum(set, n-1, sum-set[n-1]);
}
And translate it into a recursive VBA function that I plan on calling from a Sub.
So far I have:
Function SubSum(source(), n As Integer, sum)
If sum = 0 Then
SubSum = True
End If
If (n = 0 And sum <> 0) Then
SubSum = False
End If
If source(n - 1) > sum Then
SubSum = SubSum(source, n - 1, sum)
End If
SubSum = (SubSum(source, n - 1, sum) Or SubSum(source, n - 1, sum - source(n - 1)))
End Function
My issue is that returning a value in each of the basecases doesn't exit that instance of the function. So when n=0 and sum<>0, SubSum is set equal to False and the function continues to the next if statement. The dataset I'm using is small and efficiency isn't an issue, I'm just trying to understand VBA's syntax.
After doing some research I found this post:Subset sum algorithm in vba But it doesn't implement it recursively.