vendredi 27 février 2015

Permutation Algorithm in Excel VBA [on hold]

I would like to create an algorythm generating all permutations of a set number and writing it onto an Excel spreadsheet. For example: If I give it n=8 (1,2,3,4,5,6,7,8) and p=3, it will generates



1,1,1
1,1,2
1,1,3
....
1,2,1
1,2,2
...


I've heard about recursive functions but I'm not good enough to use it. I would like something like this but generationg all permutations: Combination Algorithm in Excel VBA Thanks for your help


EDIT: I've finally found it on my own. I just have to put this in my main worksheet:



1 8
1 8
1 8


It is possible to put differents start and end for each variable and it's possible to put as many variable as I want. Here is my solution:



Public Sub ListerPermutations()

Dim tableauParam() As Double
Dim p As Integer
Dim j As Integer
j = 0
p = 0

p = Application.WorksheetFunction.CountA(Feuil1.Range("$A:$A"))

ReDim tableauParam(p, 2)

For j = 1 To p
tableauParam(j, 1) = Worksheets("Feuil1").Range("A" & j).Value
tableauParam(j, 2) = Worksheets("Feuil1").Range("B" & j).Value
Next


Dim n As Integer
n = 0
For j = 1 To p
If n = 0 Then
n = (tableauParam(j, 2) - tableauParam(j, 1) + 1)
Else
n = n * (tableauParam(j, 2) - tableauParam(j, 1) + 1)
End If
Next
Worksheets("Feuil1").Range("H1").Value = n

Dim i As Integer

For j = 1 To p
Worksheets("Feuil1").Range(Chr(68 + j) & 1).Value = tableauParam(j, 1)
Next


For j = 1 To n - 1
If Worksheets("Feuil1").Range("E" & j).Value = tableauParam(1, 2) Then
Worksheets("Feuil1").Range("E" & j + 1).Value = tableauParam(1, 1)
Else
Worksheets("Feuil1").Range("E" & j + 1).Value = Worksheets("Feuil1").Range("E" & j).Value + 1
End If
Next

For j = 2 To p
For i = 2 To n
If recursive(i, j, tableauParam) Then 'Teste si c'est la valeur max sur tous les indice précédents
If Worksheets("Feuil1").Range(Chr(68 + j) & i - 1).Value = tableauParam(j, 2) Then
Worksheets("Feuil1").Range(Chr(68 + j) & i).Value = tableauParam(j, 1)
Else
Worksheets("Feuil1").Range(Chr(68 + j) & i).Value = Worksheets("Feuil1").Range(Chr(68 + j) & i - 1).Value + 1 'case(i,j)=case(i-1,j)+1
End If
Else
Worksheets("Feuil1").Range(Chr(68 + j) & i).Value = Worksheets("Feuil1").Range(Chr(68 + j) & i - 1).Value
End If
Next
Next


End Sub


Function recursive(k As Integer, l As Integer, tableauParam) As Boolean

If l > 1 Then
If Worksheets("Feuil1").Range(Chr(68 + l - 1) & k - 1).Value = tableauParam(l - 1, 2) Then
recursive = recursive(k, l - 1, tableauParam)
Else
recursive = False
End If
Else
recursive = True
End If
End Function

Aucun commentaire:

Enregistrer un commentaire