I'm trying to make a VBA code to arrange k-element subset of an n-set into some sequence. In other word, I'm trying to list all of k-permutations of n member set. For example, let's try to list all of 2-permutations of set {A,B,C} where each characters are located in the cells of Range("A1:C1")
. Here are all the permutations:
{A,B} {A,C} {B,A} {B,C} {C,A} {C,B}
The following code to implement the above task works fine if there's no duplicate in each of characters of data input:
Sub Permutation()
Dim Data_Input As Variant, Permutation_Output As Variant
Dim Output_Row As Long, Last_Column As Long
Rows("2:" & Rows.Count).Clear
Last_Column = Cells(1, Columns.Count).End(xlToLeft).Column
Data_Input = Application.Transpose(Application.Transpose(Range("A1", Cells(1, Last_Column))))
k = InputBox("Input the value of k for P(" _
& UBound(Data_Input) & " , k) where k is an integer between 2 and " _
& UBound(Data_Input) & " inclusive.", "Permutation", 1)
If k >= 2 And k <= UBound(Data_Input) Then
Output_Row = 2
ReDim Permutation_Output(1 To k)
Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, 1)
Else
MsgBox "The input [" & k & "] is invalid. The input must be an integer between 2 and " _
& UBound(Data_Input) & " inclusive."
End If
End Sub
Function Permutation_Generator(Data_Input As Variant, Permutation_Output As Variant, _
Output_Row As Long, Output_Index As Integer)
Dim i As Long, j As Long, P As Boolean
For i = 1 To UBound(Data_Input)
P = True
For j = 1 To Output_Index - 1
If Permutation_Output(j) = Data_Input(i) Then
P = False
Exit For
End If
Next j
If P Then
Permutation_Output(Output_Index) = Data_Input(i)
If Output_Index = k Then
Output_Row = Output_Row + 1
Range("A" & Output_Row).Resize(, k) = Permutation_Output
Else
Call Permutation_Generator(Data_Input, Permutation_Output, Output_Row, Output_Index + 1)
End If
End If
Next i
End Function
I am hoping I can get some help to improve its performance and to better its algorithm in order to make a good partial anagram generator, i.e. it must be able to work if there are the duplicate characters. For example, let's test to list all of characters in my name: ANA. The output should be ANA, AAN, and NAA, but my code returns nothing. For 2-permutations of my name should be AN, AA, and NA yet my code returns AN, NA, AN, and NA. I have a feeling the culprit is the following statements:
If Permutation_Output(j) = Data_Input(i) Then
P = False
Exit For
End If
though I'm not so sure. I'd be eternally grateful if someone here could help me.