Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleList all the permutations of a set of numbers
DescriptionThis example shows how to list all the permutations of a set of numbers in Visual Basic 6 recursively.
Keywordspermute, permutation, combinatorics
CategoriesAlgorithms
 
Subroutine EnumerateValues generates premutations. It takes as a parameter the index of the next value that it needs to generate. For example, it might be ready to generate the third number in a permutation of five numbers.

The routine checks the index to see if it has already assigned all of the values. If it has assigned all of the values, it loops through the m_CurrentSolution array, which holds the values in their permuted order.

If some positions in the permutation are not yet filled in, the routine loops through the values and finds those that have not yet been used in the current solution. For each unused value, the routine adds the value to the solution, recursively calls itself to assign values for the remaining entries, and then removes the value from the current solution.

 
Private m_NumValues As Integer
Private m_Used() As Integer
Private m_CurrentSolution() As Integer

Private Sub EnumerateValues(ByVal index As Integer)
Dim result As String
Dim i As Integer

    ' See if there are any values left to try.
    If index > m_NumValues Then
        ' All values are m_Used.
        ' Get a string for the current solution.
        For i = 1 To m_NumValues
            result = result & Format$(m_CurrentSolution(i)) _
                & " "
        Next i

        ' Add the current solution to the list.
        txtResults.Text = txtResults.Text & _
            result & vbCrLf
        Exit Sub
    End If

    ' Examine each value.
    For i = 1 To m_NumValues
        ' See if this value has been m_Used yet.
        If Not m_Used(i) Then
            ' It is unm_Used. Try using it.
            m_Used(i) = True
            m_CurrentSolution(index) = i

            EnumerateValues index + 1

            m_Used(i) = False
        End If
    Next i
End Sub
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated