kelly mort
Well-known Member
- Joined
- Apr 10, 2017
- Messages
- 2,169
- Office Version
- 2016
- Platform
- Windows
I want to scramble a given string then store the various combinations to a variable or an array based on what you think is cool for my demand. I came across this pieces but they are not exactly what I wanted.
Now this is what I wanna achieve; my code will take a string in the form “AABB” eg 0011, 1122 ,….. Then scramble the string making sure there is no output in the form “AABB” or “BBAA”
So for 0011, the output will be 0101, 1010, 0110, 1001. Then I store this output to a variable or an array as before. The reason being that I will later use the output by splitting the output. But don’t worry about that part that much. I have a way of dealing with things like that. Now all I need is how to get the output and then store them in the aforementioned containers, separated by any suitable list separator. I prefer a comma.
Thanks in advance
Now this is what I wanna achieve; my code will take a string in the form “AABB” eg 0011, 1122 ,….. Then scramble the string making sure there is no output in the form “AABB” or “BBAA”
So for 0011, the output will be 0101, 1010, 0110, 1001. Then I store this output to a variable or an array as before. The reason being that I will later use the output by splitting the output. But don’t worry about that part that much. I have a way of dealing with things like that. Now all I need is how to get the output and then store them in the aforementioned containers, separated by any suitable list separator. I prefer a comma.
Thanks in advance
Code:
Function Helper(s As String, Optional delim As String = ",") As String
Dim i As Long, n As Long
Dim t As String, c As String
Dim A As Variant
If Memory.exists(s) Then
Helper = Memory(s)
Exit Function
End If
'otherwise:
'Check Basis Case:
If Len(s) <= 1 Then
Helper = s
Else
n = Len(s)
ReDim A(1 To n)
For i = 1 To n
c = Mid(s, i, 1)
t = Replace(s, c, "")
A(i) = Helper(t, delim)
A(i) = c & Replace(A(i), delim, delim & c)
Next i
Helper = Join(A, delim)
End If
'record before returning:
Memory.Add s, Helper
End Function
Code:
Function scramble(s As String, Optional delim As String = ",") As String
Set Memory = CreateObject("Scripting.dictionary")
scramble = Helper(s, delim)
Set Memory = Nothing
End Function
Code:
Sub Test()
Dim s As String
Dim i As Long, n As Long
Dim A As Variant
s = "0123"
A = Split(scramble(s), ",")
For i = 0 To UBound(A)
Cells(i + 1, 1).Value = A(i)
Next i
End Sub