我需要获得所有可能组合的列表,而不是排列。
为了确保我有正确的名字,对我来说123和321是相同的,只应列出一次。
下面的代码可以满足我的需要,但我无法将其转换为MS Access vba。
对不起,我知道这是基本的,已被问过一百万次,但我找不到任何适用于我的MS Access。
Sub test_print_nCr()
print_nCr 7, 3, Range("A1")
End Sub
2
Public Function print_nCr(n As Integer, r As Integer, p As Range)
c = 1
internal_print_nCr n, r, p, 1, 1
End Function
3
Public Function internal_print_nCr(n As Integer, r As Integer, ByVal p As Range, Optional i As Integer, Optional l As Integer) As Integer
' n is the number of items we are choosing from
' r is the number of items to choose
' p is the upper corner of the output range
' i is the minimum item we are allowed to pick
' l is how many levels we are in to the choosing
' c is the complete set we are working on
If n < 1 Or r > n Or r < 0 Then Err.Raise 1
If i < 1 Then i = 1
If l < 1 Then l = 1
If c < 1 Then c = 1
If r = 0 Then
p = 1
Exit Function
End If
Dim x As Integer
Dim y As Integer
For x = i To n - r + 1
If r = 1 Then
If c > 1 Then
For y = 0 To l - 2
If p.Offset(c - 1, y) = "" Then p.Offset(c - 1, y) = p.Offset(c - 2, y)
Next
End If
p.Offset(c - 1, l - 1) = x
c = c + 1
Else
p.Offset(c - 1, l - 1) = x
internal_print_nCr n, r - 1, p, x + 1, l + 1
End If
Next
End Function
再次感谢你
答案 0 :(得分:0)
我不确定这是否是执行此操作的最佳方法,但我会使用一种二进制表示法。例如,考虑字母数n = 3的单词“boy”。这个单词有三个字母,所以你可以使用这样的东西:
001 = y, 010 = o, 011 = oy, 100 = b, 101 = by, 110 =博, 111 =男孩。
左侧可以用从i = 1到幂(2,n)-1的循环完成,并将i转换为二进制基数。因此,您唯一需要做的就是使用非null位置来构建组合。
可能在Knuth中有一些比这更有趣的东西。
答案 1 :(得分:0)
我在这里找到了这个代码,它给了我我需要的东西。你只需要创建一个1-100的数字表。以下链接中的说明
谢谢大家
Public Sub buildquery(strN As String, K As Integer)
Dim qd As DAO.QueryDef
Dim intI As Integer
Dim strsql As String
Dim strSelect As String
Dim strFrom As String
Dim strWhere As String
Set qd = CurrentDb.QueryDefs("QN")
qd.sql = "SELECT N FROM tblN WHERE N IN (" & strN & ")"
Set qd = Nothing
strSelect = "SELECT QN.N "
strFrom = "FROM QN "
strWhere = "WHERE QN_1.N > QN.N "
For intI = 1 To K - 1
strSelect = strSelect & ", QN_" & intI & ".N AS N" & intI & " "
strFrom = strFrom & ", QN AS QN_" & intI & " "
If intI < K - 1 Then
strWhere = strWhere & " AND QN_" & intI + 1 & ".N > QN_" & intI & ".N "
End If
Next
strsql = strSelect & " INTO tblCombinations " & strFrom & strWhere
DoCmd.SetWarnings False
DoCmd.RunSQL strsql
DoCmd.SetWarnings True
End Sub
然后测试
Public Sub testbuildquery()
buildquery "1,2,3,4,5,6,7", 3
End Sub