algorithm for combinations & permutations

B

Bill McKeever

Does anyone have a simple, elegant algorithm to list all
the possible combinations of n integers, taken one at a
time? For example, suppose we wish to assign the
integers 1, 2, 3, 4, 5, 6, & 7 to the variables A, B, C,
D, E, F, & G in every possible way it can be done, with
no repeated combinations. There are 5,040 ways to do
it. ( 7! ). Is there an easy way to code it?

Thanks for the help.

Bill McKeever
 
H

Harlan Grove

Bradley Dawson said:
Yes, use a recursive algorithm.

Were you a lawyer in a previous life?

Depends on how you want to do this. In VBA? Check the Google Groups
archives. This has been asked and answered several times in the past.

Using worksheet formulas? Then it depends on how much of the permutation you
want to seed. If none, then if the permutations were to be in A1:G5040 and
the letters to use were in the string "ABCDEFG" referenced by the name Pop,
enter the following formulas in row 1.

G1:
=MID(Pop,COLUMN()-INT((ROW()-1)/FACT(COLUMN()-1)),1)

F1:
=MID(SUBSTITUTE(Pop,G1,""),COLUMN()-INT(MOD(ROW()-1,
FACT(COLUMN()))/FACT(COLUMN()-1)),1)

E1:
=MID(SUBSTITUTE(SUBSTITUTE(Pop,F1,""),G1,""),COLUMN()-INT(MOD(ROW()-1,
FACT(COLUMN()))/FACT(COLUMN()-1)),1)

D1:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,E1,""),F1,""),G1,""),
COLUMN()-INT(MOD(ROW()-1,FACT(COLUMN()))/FACT(COLUMN()-1)),1)

C1:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,D1,""),E1,""),F1,""),
G1,""),COLUMN()-INT(MOD(ROW()-1,FACT(COLUMN()))/FACT(COLUMN()-1)),1)

B1:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,C1,""),
D1,""),E1,""),F1,""),G1,""),COLUMN()-INT(MOD(ROW()-1,
FACT(COLUMN()))/FACT(COLUMN()-1)),1)

A1:
=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(
SUBSTITUTE(Pop,B1,""),C1,""),D1,""),E1,""),F1,""),G1,"")

then select A1:G1 and fill down into A2:G5040.

On the other hand, if you're willing to seed the first 6 rows, enter

=MID(Pop,COLUMN(),1)

in cell A1 and fill A1 into B1:G1. Then enter these formulas for row 2.

G2:
=IF(MOD(ROW(),FACT(COLUMN()-1))=1,MID(Pop,FIND(G1,Pop)-1,1),G1)

F2:
=IF(MOD(ROW(),FACT(COLUMN()-1))=1,MID(SUBSTITUTE(Pop,G2,""),
COLUMN()-INT(MOD(ROW()-1,FACT(COLUMN()))/FACT(COLUMN()-1)),1),F1)

E2:
=IF(MOD(ROW(),FACT(COLUMN()-1))=1,MID(SUBSTITUTE(SUBSTITUTE(Pop,F2,""),
G2,""),COLUMN()-INT(MOD(ROW()-1,FACT(COLUMN()))/FACT(COLUMN()-1)),1),E1)

D2:
=IF(MOD(ROW(),FACT(COLUMN()-1))=1,MID(SUBSTITUTE(SUBSTITUTE(
SUBSTITUTE(Pop,E2,""),F2,""),G2,""),COLUMN()-INT(MOD(ROW()-1,
FACT(COLUMN()))/FACT(COLUMN()-1)),1),D1)

C2:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,D2,""),E2,""),
F2,""),G2,""),CHOOSE(1+MOD(ROW()-1,6),3,3,2,2,1,1),1)

B2:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,D2,""),E2,""),
F2,""),G2,""),CHOOSE(1+MOD(ROW()-1,6),2,1,3,1,3,2),1)

A2:
=MID(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(Pop,D2,""),E2,""),
F2,""),G2,""),CHOOSE(1+MOD(ROW()-1,6),1,2,1,3,2,3),1)

Select A2:G2 and fill down into A3:G5040.
 
B

Biff

Hi Bill,

Here's a link that will get you headed in the right
direction. The link is to a posting that unfortunately
turned into a flame contest but you can 'filter' that out.

http://tinyurl.com/lr2w

Biff
 
J

Jack Sons

Bill,

Look for simple VBA for combinations and permutations below the first dotted
line and below the second dotted line.

Jack Sons
The Netherlands

-----------------------------------------------------

'Since you asked, here it is. It is generic, i.e. it isn't written
'specifically for a given population and set size. It will do permutations
or
'combinations. It uses a recursive routine to generate the subsets, one
'routinefor combinations, a different one for permutations.



'Author: Myrna Larson <[email protected]>
'Date: 2000/07/25
'Forum: microsoft.public.Excel.misc


'To use it, you put the letter C or P (for combinations or permutations) in
'a cell. The cell below that contains the number of items in a subset. The
'Cells below are a list of the items that make up the population. They could
be
'numbers, letters and symbols, or words, etc.

'You select the top cell, or the entire range and run the sub. The subsets
'are written to a new sheet in the workbook.

Option Explicit

Dim vAllItems As Variant
Dim Buffer() As String
Dim BufferPtr As Long
Dim Results As Worksheet

Sub ListPermutations()
Dim Rng As Range
Dim PopSize As Integer
Dim SetSize As Integer
Dim Which As String
Dim N As Double
Const BufferSize As Long = 4096

Set Rng = Selection.Columns(1).Cells
If Rng.Cells.Count = 1 Then
Set Rng = Range(Rng, Rng.End(xlDown))
End If

PopSize = Rng.Cells.Count - 2
If PopSize < 2 Then GoTo DataError

SetSize = Rng.Cells(2).Value
If SetSize > PopSize Then GoTo DataError

Which = UCase$(Rng.Cells(1).Value)
Select Case Which
Case "C"
N = Application.WorksheetFunction.Combin(PopSize, SetSize)
Case "P"
N = Application.WorksheetFunction.Permut(PopSize, SetSize)
Case Else
GoTo DataError
End Select
If N > Cells.Count Then GoTo DataError

Application.ScreenUpdating = False

Set Results = Worksheets.Add

vAllItems = Rng.Offset(2, 0).Resize(PopSize).Value
ReDim Buffer(1 To BufferSize) As String
BufferPtr = 0

If Which = "C" Then
AddCombination PopSize, SetSize
Else
AddPermutation PopSize, SetSize
End If
vAllItems = 0

Application.ScreenUpdating = True
Exit Sub

DataError:
If N = 0 Then
Which = "Enter your data in a vertical range of at least 4 cells. " _
& String$(2, 10) _
& "Top cell must contain the letter C or P, 2nd cell is the number " _
& "of items in a subset, the cells below are the values from which " _
& "the subset is to be chosen."

Else
Which = "This requires " & Format$(N, "#,##0") & _
" cells, more than are available on the worksheet!"
End If
MsgBox Which, vbOKOnly, "DATA ERROR"
Exit Sub
End Sub

Private Sub AddPermutation(Optional PopSize As Integer = 0, _
Optional SetSize As Integer = 0, _
Optional NextMember As Integer = 0)

Static iPopSize As Integer
Static iSetSize As Integer
Static SetMembers() As Integer
Static Used() As Integer
Dim i As Integer

If PopSize <> 0 Then
iPopSize = PopSize
iSetSize = SetSize
ReDim SetMembers(1 To iSetSize) As Integer
ReDim Used(1 To iPopSize) As Integer
NextMember = 1
End If

For i = 1 To iPopSize
If Used(i) = 0 Then
SetMembers(NextMember) = i
If NextMember <> iSetSize Then
Used(i) = True
AddPermutation , , NextMember + 1
Used(i) = False
Else
SavePermutation SetMembers()
End If
End If
Next i

If NextMember = 1 Then
SavePermutation SetMembers(), True
Erase SetMembers
Erase Used
End If

End Sub 'AddPermutation

Private Sub AddCombination(Optional PopSize As Integer = 0, _
Optional SetSize As Integer = 0, _
Optional NextMember As Integer = 0, _
Optional NextItem As Integer = 0)

Static iPopSize As Integer
Static iSetSize As Integer
Static SetMembers() As Integer
Dim i As Integer

If PopSize <> 0 Then
iPopSize = PopSize
iSetSize = SetSize
ReDim SetMembers(1 To iSetSize) As Integer
NextMember = 1
NextItem = 1
End If

For i = NextItem To iPopSize
SetMembers(NextMember) = i
If NextMember <> iSetSize Then
AddCombination , , NextMember + 1, i + 1
Else
SavePermutation SetMembers()
End If
Next i

If NextMember = 1 Then
SavePermutation SetMembers(), True
Erase SetMembers
End If

End Sub 'AddCombination

Private Sub SavePermutation(ItemsChosen() As Integer, _
Optional FlushBuffer As Boolean = False)

Dim i As Integer, sValue As String
Static RowNum As Long, ColNum As Long

If RowNum = 0 Then RowNum = 1
If ColNum = 0 Then ColNum = 1

If FlushBuffer = True Or BufferPtr = UBound(Buffer()) Then
If BufferPtr > 0 Then
If (RowNum + BufferPtr - 1) > Rows.Count Then
RowNum = 1
ColNum = ColNum + 1
If ColNum > 256 Then Exit Sub
End If

Results.Cells(RowNum, ColNum).Resize(BufferPtr, 1).Value _
= Application.WorksheetFunction.Transpose(Buffer())
RowNum = RowNum + BufferPtr
End If

BufferPtr = 0
If FlushBuffer = True Then
Erase Buffer
RowNum = 0
ColNum = 0
Exit Sub
Else
ReDim Buffer(1 To UBound(Buffer))
End If

End If

'construct the next set
For i = 1 To UBound(ItemsChosen)
sValue = sValue & ", " & vAllItems(ItemsChosen(i), 1)
Next i

'and save it in the buffer
BufferPtr = BufferPtr + 1
Buffer(BufferPtr) = Mid$(sValue, 3)
End Sub 'SavePermutation

-------------------------------------------------------

'The GetString subroutine prompts the user for a string.
'If the length of the string is greater than 1 and less than 8,
'the GetPermutations subroutine is called --which then calls itself.
'The permutations are stored in column A of the worksheet.
'Walkenbach

Dim CurrentRow

Sub GetString()
Dim InString As String
InString = InputBox("Enter text to permute:")
If Len(InString) < 2 Then Exit Sub
If Len(InString) >= 8 Then
MsgBox "Too many permutations!"
Exit Sub
Else
ActiveSheet.Columns(1).Clear
CurrentRow = 1
Call GetPermutation("", InString)
End If
End Sub

Sub GetPermutation(x As String, y As String)
' The source of this algorithm is unknown
Dim i As Integer, j As Integer
j = Len(y)
If j < 2 Then
Cells(CurrentRow, 1) = x & y
CurrentRow = CurrentRow + 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

-----------------------------------------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top