lrobbo314
Well-known Member
- Joined
- Jul 14, 2008
- Messages
- 3,963
- Office Version
- 365
- Platform
- Windows
I feel like I am pretty good at VBA, but, I have always struggled with wrapping my head around recursion. I banged my head against the wall for hours this morning trying to figure this out. I got the code to work, but I am sure there must be a better way to do it. I would like to get better at recursion, so any pointers would be appreciated.
Basically I have an array with R, G, B, Y, and O. And I wanted to list each combination with an increasing number of elements in each group. So, the desired results are as below.
R
G
B
Y
O
RG
RB
RY
RO
GB
GY
GO
BY
BO
YO
RGB
RBY
RYO
GBY
GYO
BYO
RGBY
RBYO
GBYO
RGBYO
And here is the code I came up with...
Thanks in advance to anyone who can help give me some pointers on how to do this better.
Basically I have an array with R, G, B, Y, and O. And I wanted to list each combination with an increasing number of elements in each group. So, the desired results are as below.
R
G
B
Y
O
RG
RB
RY
RO
GB
GY
GO
BY
BO
YO
RGB
RBY
RYO
GBY
GYO
BYO
RGBY
RBYO
GBYO
RGBYO
And here is the code I came up with...
Code:
Sub Main()
Dim AR(1 To 5) As Variant 'Initialize array
Dim Index As Long: Index = 1 'Index to keep track of spot in array
Dim Length As Long: Length = 0 'Length of characters to add to string
Dim Total As Long: Total = UBound(AR) + 1 'Number of iterations per group
AR(1) = "R"
AR(2) = "G"
AR(3) = "B"
AR(4) = "Y"
AR(5) = "O"
DoIt AR, Index, Length, Total
End Sub
Sub DoIt(V As Variant, Index As Long, Length As Long, Total As Long)
Dim tmp As String
For i = Index + 1 To Total
tmp = V(Index) 'Add index value to string
If Length = 0 Then Index = Index + 1
For j = 1 To Length
tmp = tmp & V(i + j - 1) 'Add other element from recursion
Next j
Debug.Print tmp
tmp = vbNullString 'Clear out string
Next i
Index = Index + 1
If Index >= Total Then
Length = Length + 1 'Increase length of string
Index = 1
Total = Total - 1 'Decrease number of iterations
End If
If Total > 1 Then DoIt V, Index, Length, Total
End Sub
Thanks in advance to anyone who can help give me some pointers on how to do this better.