09. april 2003 - 14:58Der er
6 kommentarer og 1 løsning
Genere mulige udfald
Hej
jeg har et spørgsmål. Hvis jeg eksv. har 5 forskellige tal (1,2,3,4,5) og vil vælge 3 (uden tilbagelægning) så kan jeg lave 10 forskellige kombinationer.
Spørgsmålet er: kan jeg få Excel til at genere de mulige kombinationer dvs. 123, 124, 125 osv.????
Rettelse: Det forrige link lister kun alle permutationerne.
Denne her lister alle kombinationer, af n elementer taget k af gangen.
Indsæt i et nyt VBA modul ---------------------------------
' ' Credit: Charles Griffin <cgriffin@ANL.GOV> '
'Global Variables Option Explicit Dim colCounter() As Integer Dim colBottom() As Integer Dim colTop() As Integer Dim loopIndex Dim rowNum As Integer Dim k As Integer Dim numCombins As Integer Dim outputrng As Range
Sub ListCombinations() Dim colNum As Integer Dim n As Integer MsgBox "Lists all of the combinations of n items taken k at a time." n = InputBox("n= ", "n items") k = InputBox("k= ", "k at a time") ReDim colCounter(1 To k) ReDim colBottom(1 To k) ReDim colTop(1 To k) 'Initialize values rowNum = 1 For colNum = 1 To k colBottom(colNum) = colNum colTop(colNum) = colNum + n - k colCounter(colNum) = 0 Next 'ActiveSheet.Range("A:IV").ClearContents '**Put this in if you wantthe wksht cleared** Set outputrng = Selection numCombins = Application.Combin(n, k) MsgBox "The number of combinations is " & numCombins loopIndex = 0 Call forLoop(colBottom(1), colTop(1)) End Sub
Sub rowPrint() Dim colNum As Integer If rowNum > numCombins Then End For colNum = 1 To k outputrng(rowNum, colNum) = colCounter(colNum) Next rowNum = rowNum + 1 End Sub
Sub forLoop(bottom As Integer, top As Integer) Dim colNum As Integer Dim i As Integer loopIndex = loopIndex + 1 If (loopIndex > k) Then Call rowPrint Else colNum = loopIndex For colCounter(colNum) = colBottom(colNum) To colTop(colNum) Call forLoop(colBottom(colNum), colTop(colNum)) Next colCounter(colNum) colBottom(loopIndex) = colBottom(loopIndex) + 1 For i = loopIndex + 1 To k colBottom(i) = colBottom(i - 1) + 1 Next End If loopIndex = loopIndex - 1 End Sub
------------------------------
Koden kunne vist godt trænge til at blive strammet lidt op, men den ser ud til at virke.
Synes godt om
Ny brugerNybegynder
Din løsning...
Tilladte BB-code-tags: [b]fed[/b] [i]kursiv[/i] [u]understreget[/u] Web- og emailadresser omdannes automatisk til links. Der sættes "nofollow" på alle links.