使用vba选择长度为3的唯一子集

时间:2012-04-20 23:38:10

标签: excel vba excel-vba

我正在尝试从1到6之间的整数生成长度为3的唯一子集。我已经使用了下面的许多版本的脚本,但似乎总是遇到某种问题。如果有人能给我一些指示,那就太棒了。感谢。

Sub permuteTest()

num = 6
cRow = 1

For i = 1 To num - 2

    For j = 2 To num - 1

        For k = 3 To num

            Cells(cRow, 1).Value = i
            Cells(cRow, 2).Value = j
            Cells(cRow, 3).Value = k

            cRow = cRow + 1

        Next k
    Next j
Next i

End Sub

2 个答案:

答案 0 :(得分:1)

像这样:

Sub permuteTest()

num = 6
cRow = 1

    For i = 1 To num - 2
        For j = i + 1 To num - 1
            For k = j + 1 To num
                Cells(cRow, 1).Value = i
                Cells(cRow, 2).Value = j
                Cells(cRow, 3).Value = k

                cRow = cRow + 1
            Next k
        Next j
    Next i

End Sub

答案 1 :(得分:1)

这个例程说明了如何解决。它生成字符串元组“3,4,1”,但如果您愿意,可以修改为使用数组。不容易阅读,但如果你一步一步都会清楚。为了紧凑,我没有声明变量,所以运行WITHOUT Option Explicit。

Const T = 3 ' generate 3-tuples
Const N = 6 ' using digits 1,...,6

Private Sub Permute()
    Dim cTuples As New Collection: Call cTuples.Add(Empty)      ' start w empty tuple (rank 0)
    For i = 1 To T: Set cTuples = NewTuples(cTuples, N): Next i ' increase tuple rank T times using N digits
    For Each vTuple In cTuples: Debug.Print vTuple: Next        ' display the results
End Sub

' helper func: turn a set of T-tuples into T+1 tuples
Private Function NewTuples(Tuples As Collection, N As Integer) As Collection
    Set NewTuples = New Collection
    For Each vOldTuple In Tuples
        For i = 1 To N: NewTuples.Add (AppendToTuple(vOldTuple, i)): Next
    Next
End Function

' helper func: turn a single T tuple into a T+1 tuple
Private Function AppendToTuple(Tuple, i)
    If IsEmpty(Tuple) Then AppendToTuple = i Else AppendToTuple = Tuple & "," & i
End Function

生成的字符串元组debug.print'到Immed Window(ctrl-G):

1,1,1
1,1,2
1,1,3
1,1,4
1,1,5
1,1,6
1,2,1
1,2,2
...
6,6,5
6,6,6