-
Hi everyone!
I've been bothering with this problem for about a pair of
months (without getting a solution!). The question in fact
is simple: given a word of a n length, getting all the
possible (n!) anagrams. If there are more words, space has
to be considered as a character. For example:
- one = one, neo, eon, oen, noe, eno
I have tried some recursive processes but... no way! I
really can't figure out how to solve this!
If you have any idea...
Thanks
-
you need to make use of VBs Collection object, a collection is like a list that you can just add to using its add method. Then you can loop through all the Items using a For Each Loop
Here is the code for a form, when you press the command button it puts all the anagrams of text1 into list1 I've included the code to do this as a simple example of collections. The Anagrams returns a collection of all the possible anagrams of a word
Code:
Option Explicit
Private Sub Command1_Click()
Dim c As Collection
Dim v As Variant
Set c = Anagrams(Text1.Text) 'use the set keyword to set one collection = to another
List1.Clear
'use the for each loop to loop through all the Items in a collection
For Each v In c
List1.AddItem v
Next v
End Sub
Public Function Anagrams(Word As String) As Collection
Dim retval As New Collection
Dim varTemp As Variant
Dim i As Integer
Dim colltemp As Collection
Select Case Len(Word)
Case 0 'If we're given an empty string
retval.Add ""
Case Else
'we go through selecting each letter of our word to be the first
For i = 1 To Len(Word)
'Find all anagrams of the word minus that letter
Set colltemp = Anagrams(Left$(Word, i - 1) & Mid$(Word, i + 1))
'Now loop through all these and add the selected letter to the front
'then add them to the output collection
For Each varTemp In colltemp
retval.Add (Mid$(Word, i, 1) & varTemp)
Next varTemp
Next i
End Select
Set Anagrams = retval
End Function
hope this helps
-