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 in Visual Basic 2005
DescriptionThis example shows how to list all the permutations of a set of numbers in Visual Basic 2005.
Keywordspermute, permutation, combinatorics, factorial, VB.NET
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)
    ' See if there are any values left to try.
    If index > m_NumValues Then
        ' All values are Used.
        ' Get a string for the current solution.
        Dim result As String = ""
        For i As Integer = 1 To m_NumValues
            result &= Format$(m_CurrentSolution(i)) & " "
        Next i

        ' Add the current solution to the list.
        lstResults.Items.Add(result)
        Exit Sub
    End If

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

            EnumerateValues(index + 1)

            m_Used(i) = False
        End If
    Next i
End Sub
 
For information on other algorithms (albeit in Visual Basic 6), see my book Ready-to-Run Visual Algorithms.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated