Recursion, a few basic cases in VBA
I'm trying to grab 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 to call from 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 problem is that returning a value in each of the base bases does not come out of this function instance. So when n = 0 and sum <> 0, SubSum is set to False and the function continues with the next if statement. The dataset I am using is small and efficiency is not an issue, I am just trying to understand the VBA syntax.
After some research, I found this post: Summing Sums Algorithm in vba But it doesn't implement it recursively.
source to share
or use elseif to avoid the exit function
Sub test()
Dim arr() As Variant
Dim sum As Long
Dim n As Long
Dim result As Boolean
arr = Array(3, 34, 4, 12, 5, 2)
n = 9
result = SubSum(arr, UBound(arr), n)
End Sub
Function SubSum(source As Variant, n As Long, sum As Long) As Boolean
If sum = 0 Then
SubSum = True
ElseIf (n = 0 And sum <> 0) Then
SubSum = False
ElseIf source(n - 1) > sum Then
SubSum = SubSum(source, n - 1, sum)
Else
SubSum = (SubSum(source, n - 1, sum) Or SubSum(source, n - 1, sum - source(n - 1)))
End If
End Function
source to share
My problem ..... and the function continues with the next if statement.
To fix this problem, you will need to use Exit Function
.
for example
'
'~~> Rest of the code
'
If sum = 0 Then
SubSum = True
Exit Function
ElseIf (n = 0 And sum <> 0) Then
SubSum = False
Exit Function
End If
'
'~~> Rest of the code
'
source to share