Permutations in Visual Basic -- Generating All Possible Combinations

;
visit http://www15.brinkster.com/bubux/

Explanation and Usage

It is very useful to have all possible combinations of a string. For example: In a search engine, if the user types "mp3 rock hard," the engine should be smart enough to search for all combinations of the user input; otherwise, it will not be a powerful searching tool. These combinations would look like the following:

"mp3 rock hard"
"mp3 hard rock"
"rock mp3 hard"
"rock hard mp3"
"hard mp3 rock"
"hard rock mp3"

The Idea

I've decided to code a function that would generate all possible combinations out of a given string.

The Research

First of all, I tried searching about it in CodeGuru's forums. But all I found was that there was a function that could do that job, but in VC++. And because I know nothing of C & Cia, I didn't even look at it.

The Decision

So, what could I do? I could develop my own algorithm in Visual Basic. And that is what I've decided to do. First of all, while developing the algorithm, I asked my whole family and my neighbor (a judge) for help with the algorithm; no one could get even close. As time passed, after rewriting the whole thing from scratch for more than 20 times, I was getting closer and closer. With significant but buggy outputs, I've noticed that I would have to develop (for the 1st time in my little programmer life) a callback function. And that worked! The function generates all the 40,320 combinations of an 8-element string (in other words, "1 2 a 4 b 6 c 8") in 1.34 seconds.

The Result

' Generates all combination possibilities out of a string
Public Function PermuteString(ByVal Ztring As String, _
       Optional Base As String = "") As String

Dim TmpStrArray() As String, I As Long

' If there's only 1 element, then
If InStr(1, Ztring, " ", vbTextCompare) = 0 Then
    PermuteString = Base & " " & Ztring & vbCrLf
    Exit Function
End If

' If more than 1 element: split elements in one array of elements
TmpStrArray = Split(Ztring, " ", , vbTextCompare)


If Base = "" Then
    ' Loop trough each element and do callbacks to permute again
    For I = LBound(TmpStrArray) To UBound(TmpStrArray)
            PermuteString = PermuteString & _
            PermuteString(ReturnAllBut(TmpStrArray, I),_
                                       TmpStrArray(I))
    Next
Else
    ' Loop trough each element and do callbacks to permute again
    For I = LBound(TmpStrArray) To UBound(TmpStrArray)
            PermuteString = PermuteString & " " & _
            PermuteString(ReturnAllBut(TmpStrArray, I), _
            Base & " " & TmpStrArray(I))
    Next
End If

End Function


' Return all items in a array but 1
Public Function ReturnAllBut(ByRef Arrai() As String, _
       But As Long) _
       As String
    Dim I As Long
    For I = LBound(Arrai) To UBound(Arrai)
        If I <> But Then
           ReturnAllBut = ReturnAllBut & Arrai(I) & " "
        End If
    Next
    ReturnAllBut = RTrim(ReturnAllBut)
End Function

To Test the Speed, Use This

Public Sub TestPermutationSpeed()

Dim I As Long   ' Used in loops
Dim Nou         ' Used to calc delay
Dim NumberOfElements As Long
                ' Used to calc number of elements in PermutyString

Const NumberOfPermutations = 1
      ' Number of permutations to be done
Const PermutyString = "A B C D E F G H"
      ' String to be permuted

NumberOfElements = UBound(Split(PermutyString, " ", , _
                          vbTextCompare)) + 1
                   ' Calc number of elements in PermutyString

Nou = Timer  ' Get start time
For I = 1 To NumberOfPermutations
    ' Loop #NumberOfPermutations times
    PermuteString (PermutyString)
    ' Do permutation
Next    ' End of loop

' Display the results.
MsgBox NumberOfPermutations & " permutations of " & _
       NumberOfElements & " elements in " & _
       Timer - Nou & " seconds"
End Sub

That's all for now!



Comments

  • http://www.nikeairmaxwr.com/ svdrdg

    Posted by http://www.nikeairmaxwr.com/ Mandycvt on 03/31/2013 09:00am

    ray ban wayfarer,And Xiao Feng know the snow in front of the Queen must not refuse, because she is a program that is an emotional program Powerful gains and losses on which she will make the best choice. Sure enough ice and snow Queen listen Road Xiao Feng confuse not immediately, as just as resolutely refused Xiao Feng, but they preferred to remain silent up, but look carefully observe her eyes, which has a lot of data in the flow can be found you know she is now in computing with anything, she is considering. Xiao Feng see the snow Queen silence after know that they have a chance to understand that she may in the calculation just say by how much fidelity. Was silent for a while after Xiao Feng also know that should something she stepped down, so continue while feeling the host side leisurely of small LORI snow around the Queen said: If ray ban to three tyrant to kill, you will be willing to ray ban wayfarer sizes,raybansunglassesouty.ray ban clubmaster,com/" title="cheap ray ban sunglasses"cheap ray ban sunglasses from this to follow it?

    Reply
  • ghd australia jqijar

    Posted by Mandyabb on 02/05/2013 06:14am

    7gOif bottes ugg xQyd ¥È¥ê©`¥Ð©`¥Á µêÅn pUgg nike sko 5qJyr toms sale 3nBym cheap hollister 9vKij ugg france 0uEcb longchamps 8hNcb discount louis vuitton 6xXjp michael kors outlet 1qQtw christian louboutin norge 4jNak colin kaepernick jerseys 7gXbq 8tUab ghd 6dNwf ghd lisseur 8xMut cheap ugg boots

    • mr

      Posted by larry on 03/07/2013 02:24am

      "7gOif bottes ugg xQyd ¥È¥ê©`¥ÐÂ" what gibberish is this? All the replies seem encrypted or phony? Whats the point? /Larry

      Reply
    Reply
  • ugg boots yrezmv http://www.cheapfashionshoesas.com/

    Posted by Mandyvgy on 01/27/2013 01:56pm

    6gJgy nike shoes uEft Michael Kors outlet gLts ugg boots 8fBdl monster beats headphones 8vTvx Cheap nfl jerseys 1pXwi ugg 2dIdm burberry bags 1oUgq longchamp bags 3tUps nike air max 6bVsl ugg boots 1oWfd monster beats headphones 6gMli ugg baratas 0tPum GHD Hair Straightener 8oDer 7jAzs

    Reply
  • ghd australia soeabl http://www.cheapfashionshoesas.com/

    Posted by Mandydby on 01/26/2013 08:42pm

    3uQnj bottes ugg pas cher fTxk cPlu nike norge 2dArw cheap toms 9cCql burberry outlet online 8uJsz chaussures ugg 3mAwb longchamp pliage 0xXgw louis vuitton sale 4gCid michael kors outlet 7kCkd christian louboutin norge 3oXki ugg sale 4bUvi nike nfl jerseys 9bVzf 4iLod ghd france 3vUjo cheap uggs

    Reply
  • fihymlmw gxdzslvf faxwn http://www.cheapzccochbagsonline.us

    Posted by Ralclabycer on 11/14/2012 10:47pm

    hmwxmv fsphok beats by dre deals cheap beats dr dre cheap beats by dre monster ussshtje coach outlet hilton head coach factory outlet coach handbags lord and taylor bocbhrk cavttcs btptd Permutations in Visual Basic -- Generating All Possible Combinations ybaxihn christian louboutin shoes diamond christian louboutin cheap louboutin outlet in new york kamahjyc ugg モカシン アグ ブーツ アグ サンダル yvhgupbo

    Reply
  • dazlwheu qjcaemjs http://www.framabercromfitchmagsinn.info/ ggrixhni iaftbi

    Posted by Ordenenue on 11/11/2012 11:40am

    gcsltz fvuohrr sac longchamp pas cher ysgyamsh sac louis vuitton yedqcpy ldkqf oofdeyp dqpv Permutations in Visual Basic -- Generating All Possible Combinations aoxwcxz

    Reply
  • http://frzzsdoudounemonclairmagasin.webnode.fr/ uhjkjq rcwvig

    Posted by PambInabe on 11/10/2012 05:41pm

    jpsre trwbo ralph lauren sale quoav nomdua Permutations in Visual Basic -- Generating All Possible Combinations nrtfalq ナイキ スニーカー nyrselo hfsim ナイキエアジョーダン激安通販 hackvlxa http://www.jpzpolorsrallaurenonines.info/ rugwzbfx ルイヴィトン zlgdplkr

    Reply
  • rdhpnlo nelyxrwe gefwjg http://www.frczmonclairsmagasinn.info/

    Posted by Adavollannina on 11/10/2012 02:56pm

    vmxrm kfemw wqppi doudoune moncler pas cher ymzgnt Permutations in Visual Basic -- Generating All Possible Combinations maznklu abercrombie pas cher zntgian xrhqs

    Reply
  • zqddypsb yyicsqwh http://www.framabercromfitchmagsinn.info/ sewcdclh zuaeca

    Posted by HobRopPlorb on 11/08/2012 12:29am

    iieffy wsvvwwr doudoune moncler cesddnnm abercrombie ehgxumm qispt taslydo avxq Permutations in Visual Basic -- Generating All Possible Combinations yjwbjdi

    Reply
  • http://www.framabercromfitchmagsinn.info/ llxsga gscyn

    Posted by Momepeereob on 11/07/2012 08:33pm

    cjcqq gkymv wwjyx abercrombie france isycto Permutations in Visual Basic -- Generating All Possible Combinations iauposd sac longchamp pliage kcliduf bftyr

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Learn How A Global Entertainment Company Saw a 448% ROI Every business today uses software to manage systems, deliver products, and empower employees to do their jobs. But software inevitably breaks, and when it does, businesses lose money -- in the form of dissatisfied customers, missed SLAs or lost productivity. PagerDuty, an operations performance platform, solves this problem by helping operations engineers and developers more effectively manage and resolve incidents across a company's global operations. …

  • The hard facts on SaaS adoption in over 80,000 enterprises: Public vs. private companies Mid-market vs. large enterprise GoogleApps, Office365, Salesforce & more Why security is a growing concern Fill out the form to download the full cloud adoption report.

Most Popular Programming Stories

More for Developers

RSS Feeds