+ Reply to Thread
Results 1 to 10 of 10

Generate all possible combinations between 3 letters

Hybrid View

  1. #1
    Registered User
    Join Date
    02-27-2013
    Location
    Porto
    MS-Off Ver
    Excel 2010
    Posts
    94

    Generate all possible combinations between 3 letters

    Hi guys,

    Could you help me with this?

    Basically what I need is:

    If I have the letters "abc": It would give me: "abc", "acb", "cab", "cba", "bac", "bca".

    The programme I have is only giving me "abc".

    Can you please help me?

    Private Sub CommandButton1_Click()
    
    Range("A1", Columns("A").SpecialCells(xlCellTypeLastCell)).Delete
    
    Dim Letters As String
        Dim WriteMe As String
        Dim ChooseThese() As Boolean
        Dim HowMany As Long
        Dim i As Long, EndNow As Boolean
        
        Letters = "abc"
        HowMany = 3
        
        ReDim ChooseThese(1 To Len(Letters))
        For i = 1 To HowMany
            ChooseThese(i) = True
        Next i
        
        Do
            For i = 1 To Len(Letters)
                If ChooseThese(i) Then
                    Sheet1.Cells(1 + j, 1) = Sheet1.Cells(1 + j, 1) & Mid(Letters, i, 1)
                End If
            Next i
            j = j + 1
            ChooseThese = NextChoices(ChooseThese, EndNow)
        Loop Until EndNow
        
    End Sub
    
    
    Function NextChoices(ByVal arrChoices As Variant, Optional ByRef Overflow As Boolean) As Variant
        Dim Pointer As Long, outPoint As Long
        
        Overflow = True
        
        Pointer = LBound(arrChoices)
        
        Do Until arrChoices(Pointer)
            Pointer = Pointer + 1
        Loop
        outPoint = LBound(arrChoices) - 1
        Do
            If arrChoices(Pointer) Then
                outPoint = outPoint + 1
                arrChoices(Pointer) = False
                arrChoices(outPoint) = True
                Pointer = Pointer + 1
            Else
                arrChoices(outPoint) = False
                arrChoices(Pointer) = True
                Overflow = False
                Exit Do
            End If
        Loop Until UBound(arrChoices) < Pointer
        
        NextChoices = arrChoices
        
    End Function

  2. #2
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Generate all possible combinations between 3 letters

    Hi rcprito,

    Try the following code:
    Option Explicit
    
    Dim wsGblOutput As Worksheet
    Dim iGblOutputRow As Long
    
    Private Sub CommandButton1_Click()
    
        Dim Letters As String
        
        'Clear the output Area
        Range("A1", Columns("A").SpecialCells(xlCellTypeLastCell)).Delete
        
        'Create the Source String for Permulations
        Letters = "abc"
        
        'Initialize Global variables
        Set wsGblOutput = ActiveSheet
        iGblOutputRow = 1
        
        'Generate Permutations of the 'Source String' and
        'Output results in Column 'A' of the Output Worksheet
        Call GetPermutationsOfString("", Letters)
        
        'Clear object pointers
        Set wsGblOutput = Nothing
                
    End Sub
     
    Sub GetPermutationsOfString(x As String, y As String)
      'Reference: http://spreadsheetpage.com/index.php/tip/generating_permutations/
      '
      'Usage:  GetPermutationsOfString("", sOriginalString)
      '
      'Number of Permuations for Original String Length:
      ' 1            1
      ' 2            2
      ' 3            6
      ' 4           24
      ' 5          120
      ' 6          720
      ' 7        5,040
      ' 8       40,320
      ' 9      362,880
      '10    3,628,800
      '11   39,916,800
      '12  479,001,600
      
      '
      'For Excel 2003  the Maximum original string length is 8 (generates  40,328 rows - Excel Max rows =    65,536)
      'For Excel 2007+ the Maximum original string length is 9 (generates 363,880 rows - Excel Max rows = 1,048,576)
      
      Dim i As Integer
      Dim j As Integer
      
      j = Len(y)
      If j < 2 Then
        wsGblOutput.Cells(iGblOutputRow, 1) = x & y
        iGblOutputRow = iGblOutputRow + 1
      Else
        For i = 1 To j
          Call GetPermutationsOfString(x + Mid(y, i, 1), Left(y, i - 1) + Right(y, j - i))
        Next
      End If
      
    End Sub
    Lewis
    Last edited by LJMetzger; 09-17-2015 at 07:51 PM. Reason: Added items in red to code which were omitted in error.

  3. #3
    Registered User
    Join Date
    02-27-2013
    Location
    Porto
    MS-Off Ver
    Excel 2010
    Posts
    94

    Re: Generate all possible combinations between 3 letters

    Hello. Thank you for your answer.

    It doesn't work. What do I have to change? I can't understand.

    Thank you

  4. #4
    Forum Expert
    Join Date
    10-06-2008
    Location
    Canada
    MS-Off Ver
    2007 / 2013
    Posts
    5,693

    Re: Generate all possible combinations between 3 letters

    This file was hanging around on my machine.
    See attached
    Attached Files Attached Files

  5. #5
    Registered User
    Join Date
    02-27-2013
    Location
    Porto
    MS-Off Ver
    Excel 2010
    Posts
    94

    Re: Generate all possible combinations between 3 letters

    It's working. Thanks a lot!

    Is there any other way to introduce more than 12 letters?

    Thank you!

  6. #6
    Forum Expert shg's Avatar
    Join Date
    06-20-2007
    Location
    The Great State of Texas
    MS-Off Ver
    2010, 2019
    Posts
    40,689

    Re: Generate all possible combinations between 3 letters

    The file would be over 5000 MB. What would you do with it if you had it?
    Entia non sunt multiplicanda sine necessitate

  7. #7
    Registered User
    Join Date
    02-27-2013
    Location
    Porto
    MS-Off Ver
    Excel 2010
    Posts
    94

    Re: Generate all possible combinations between 3 letters

    Nothing really. Curiosity!

    I have another doubt, could you please help me?

    From the programme above, how from 10 letters can we write all the possible words with 3 of these letters?

    Thank you

    Option Explicit
    
    Dim var As New Collection
    Dim CurrentRow As Long
    
    Sub GetString()
    
        Dim InString As String
        InString = InputBox("Enter text to permute:")
        If Len(InString) < 2 Then Exit Sub
        If Len(InString) >= 12 Then
            MsgBox "Too many permutations!"
            Exit Sub
        Else
            ActiveSheet.Columns(1).ClearContents
            Call GetPermutation("", InString)
        End If
        For CurrentRow = 1 To var.Count
            Range("A" & CurrentRow).Value = var.Item(CurrentRow)
        Next CurrentRow
        CurrentRow = Empty
        Set var = Nothing
        
    End Sub
    
    Sub GetPermutation(x As String, y As String)
       
        Dim i As Integer, j As Integer
        j = Len(y)
        If j < 2 Then
            On Error Resume Next
            var.Add CStr(x & y), (x & y)
            Err.Clear: On Error GoTo 0: On Error GoTo -1
        Else
            For i = 1 To j
                Call GetPermutation(x + Mid(y, i, 1), _
                Left(y, i - 1) + Right(y, j - i))
            Next
        End If
        
    End Sub
    
    Sub Clear_Result()
    Range("A:A").ClearContents
    End Sub

  8. #8
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Generate all possible combinations between 3 letters

    Items in red in post #2 were omitted in error. I apologize for the inconvenience.

    Lewis

  9. #9
    Forum Expert
    Join Date
    01-23-2013
    Location
    USA
    MS-Off Ver
    Microsoft 365 aka Office 365
    Posts
    3,863

    Re: Generate all possible combinations between 3 letters

    From the programme above, how from 10 letters can we write all the possible words with 3 of these letters?
    See the following code, which outputs the results in Column 'A' and Column 'B' of the Active Sheet:
    Option Explicit
    
    Dim wsGblOutput As Worksheet
    Dim iGblOutputRow As Long
    
    Sub GeneratePermutationsFromCombinationsTakenNatOneTime()
      'This generates a list of permutations from Combinations taken 3 at a time from an original string
      
      Const nThreeItemsAtOneTIME = 3
      
      Dim i As Long
      Dim sReturnArray() As String
      Dim sOriginalString As String
      
      'Create the Source String for Combinations and Permulations
      sOriginalString = "abcdefghij"
      
      'Initialize the Output resources
      Set wsGblOutput = ActiveSheet
      iGblOutputRow = 1
      
      'Clear the output Area
      wsGblOutput.Range("A1:B" & rows.Count).ClearContents
        
      'Create an array of Combinations of the original string taken N at one time
      sReturnArray = GenerateCombinationsTakenNatOneTime(sOriginalString, nThreeItemsAtOneTIME)
      
      'Create Permutations from each Combination
      For i = LBound(sReturnArray) To UBound(sReturnArray)
        'Generate Permutations of the 'Source String' and
        'Output results in Column 'A' of the Output Worksheet
        wsGblOutput.Cells(iGblOutputRow, "A") = sReturnArray(i)
        Call GetPermutationsOfString("", sReturnArray(i))
      Next i
      
      'Clear object pointers
      Set wsGblOutput = Nothing
      
    End Sub
    
     
    Sub GetPermutationsOfString(x As String, y As String)
      'Reference: http://spreadsheetpage.com/index.php/tip/generating_permutations/
      '
      'Usage:  GetPermutationsOfString("", sOriginalString)
      '
      'Number of Permuations for Original String Length:
      ' 1            1
      ' 2            2
      ' 3            6
      ' 4           24
      ' 5          120
      ' 6          720
      ' 7        5,040
      ' 8       40,320
      ' 9      362,880
      '10    3,628,800
      '11   39,916,800
      '12  479,001,600
      
      '
      'For Excel 2003  the Maximum original string length is 8 (generates  40,328 rows - Excel Max rows =    65,536)
      'For Excel 2007+ the Maximum original string length is 9 (generates 363,880 rows - Excel Max rows = 1,048,576)
      
      Dim i As Integer
      Dim j As Integer
      
      j = Len(y)
      If j < 2 Then
        wsGblOutput.Cells(iGblOutputRow, "B") = x & y
        iGblOutputRow = iGblOutputRow + 1
      Else
        For i = 1 To j
          Call GetPermutationsOfString(x + Mid(y, i, 1), Left(y, i - 1) + Right(y, j - i))
        Next
      End If
      
    End Sub
    
    
    Function GenerateCombinationsTakenNatOneTime(sOriginalString As String, n As Long) As Variant
      'This returns an array of combinations taken N at one time from an 'Original String'
    
      Dim vElements As Variant
      Dim vResult As Variant
      Dim sReturnArray() As String
      Dim lRow As Long
      Dim i As Long
      Dim iLastIndex As Integer
      
      'Put  'Original String'
      iLastIndex = Len(sOriginalString)
      ReDim vElements(1 To iLastIndex)
        
      'Divide the 'Original String' into an array of Characters
      For i = 1 To iLastIndex
        vElements(i) = Mid(sOriginalString, i, 1)
      Next i
        
      'Generate an array of Combinations taken N at one time
      lRow = 0
      ReDim vResult(1 To iLastIndex)
      Call CombinationsNP(vElements, n, vResult, lRow, 1, 1, sReturnArray)
      
      'Return the Result Array to the calling routine
      GenerateCombinationsTakenNatOneTime = sReturnArray
    
    End Function
    
     
    Sub CombinationsNP(ByVal vElements As Variant, _
                       ByVal p As Long, _
                       ByRef vResult As Variant, _
                       ByRef lRow As Long, _
                       ByVal iElement As Integer, _
                       ByVal iIndex As Integer, _
                       ByRef sReturnArray() As String)
      'This generates a list of combinations of a string taken n at one time in sReturnArray()
      '
      '
      'Reference: http://www.rpbridge.net/7z78.htm     'Table of Factorials and Combinations
      'Tutorial: http://www.stat.wisc.edu/~ifischer/Intro_Stat/Lecture_Notes/APPENDIX/A1._Basic_Reviews/A1.2_-_Perms_and_Combos.pdf
                       
    
      Dim i As Long
      Dim ii As Long
      Dim sValue As String
     
      For i = iElement To UBound(vElements)
        vResult(iIndex) = vElements(i)
        If iIndex = p Then
          lRow = lRow + 1
        
          'Result is here
          sValue = ""
          For ii = LBound(vResult) To UBound(vResult)
            sValue = sValue & vResult(ii)
          Next ii
          ReDim Preserve sReturnArray(1 To lRow)
          sReturnArray(lRow) = sValue
        
        Else
            Call CombinationsNP(vElements, p, vResult, lRow, i + 1, iIndex + 1, sReturnArray)
        
        End If
      Next i
      
    End Sub
    Lewis
    Last edited by LJMetzger; 09-18-2015 at 12:16 PM. Reason: Line in red corrects error that erased entire sheet

  10. #10
    Registered User
    Join Date
    02-27-2013
    Location
    Porto
    MS-Off Ver
    Excel 2010
    Posts
    94

    Re: Generate all possible combinations between 3 letters

    Thanks a lot. It's perfect!

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. [SOLVED] Generate Combinations Using VBA
    By NeedForExcel in forum Excel Programming / VBA / Macros
    Replies: 21
    Last Post: 06-06-2021, 01:10 AM
  2. Finding combinations of 8 letters
    By macaonghus in forum Excel Programming / VBA / Macros
    Replies: 4
    Last Post: 02-19-2015, 02:20 AM
  3. Generate all possible combinations
    By muttleychess in forum Excel General
    Replies: 7
    Last Post: 09-22-2014, 02:39 PM
  4. How to generate all possible combinations of nine cities
    By Nikolas1988 in forum Excel General
    Replies: 2
    Last Post: 06-09-2014, 09:21 AM
  5. [SOLVED] how to generate combinations in excel
    By sgrondines in forum Excel General
    Replies: 5
    Last Post: 08-13-2012, 07:24 AM
  6. Generate combinations
    By cjt_choccy in forum Excel General
    Replies: 6
    Last Post: 11-20-2011, 02:51 PM
  7. Find all possible combinations of letters
    By Double-R in forum Excel Programming / VBA / Macros
    Replies: 5
    Last Post: 08-26-2010, 09:09 AM

Bookmarks

Posting Permissions

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

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1