Results 1 to 3 of 3

Thread: A strange problem...

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jul 2000
    Location
    Italy
    Posts
    90
    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

  2. #2
    Frenzied Member
    Join Date
    Mar 2000
    Posts
    1,089
    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

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Jul 2000
    Location
    Italy
    Posts
    90
    OK! Thanks a lot! ;-)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width