|
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件 ★ 免费下载 ★ ★ 使用帮助★
直接递归,实在是太费脑子了,因为已知4列,干脆就直接写循环了。每一列的数量不固定,这个没办法只能递归取数,完了就是纯循环。
- Sub Main()
- tt = Timer
- ar = Range("a1:d8").Value
- br = Range("f2:h5").Value
- n = Range("i2").Value
- ReDim cr(1 To 4)
- For i = 1 To 4
- cr(i) = GetNumofColumn(ar, i)
- Next
- ar = cr
- ReDim result(1 To 50000, 1 To n)
-
- For i1 = br(1, 2) To br(1, 3)
- For i2 = br(2, 2) To br(2, 3)
- For i3 = br(3, 2) To br(3, 3)
- For i4 = br(4, 2) To br(4, 3)
- If i1 + i2 + i3 + i4 = n Then
- j = 0
- If i1 > 0 Then j = j + 1: cr(j) = CombinM_N(ar(1), i1)
- If i2 > 0 Then j = j + 1: cr(j) = CombinM_N(ar(2), i2)
- If i3 > 0 Then j = j + 1: cr(j) = CombinM_N(ar(3), i3)
- If i4 > 0 Then j = j + 1: cr(j) = CombinM_N(ar(4), i4)
- If j < 4 Then
- ReDim temp(1, 1)
- For i = j + 1 To 4
- cr(i) = temp
- Next
- End If
- For j1 = 1 To UBound(cr(1))
- For j2 = 1 To UBound(cr(2))
- For j3 = 1 To UBound(cr(3))
- For j4 = 1 To UBound(cr(4))
- k = k + 1
- For k1 = 1 To UBound(cr(1), 2)
- If k1 <= n Then result(k, k1) = cr(1)(j1, k1)
- Next
- For k2 = 1 To UBound(cr(2), 2)
- If k1 - 1 + k2 <= n Then result(k, k1 - 1 + k2) = cr(2)(j2, k2)
- Next
- For k3 = 1 To UBound(cr(3), 2)
- If k1 + k2 - 2 + k3 <= n Then result(k, k1 + k2 - 2 + k3) = cr(3)(j3, k3)
- Next
- For k4 = 1 To UBound(cr(4), 2)
- If k1 + k2 + k3 - 3 + k4 <= n Then result(k, k1 + k2 + k3 - 3 + k4) = cr(4)(j4, k4)
- Next
- Next
- Next
- Next
- Next
- End If
- Next
- Next
- Next
- Next
- Range("k1").Resize(k, n).Value = result
- MsgBox "组合数量: " & k & Chr(10) & "用时: " & Timer - tt
- End Sub
- Function GetNumofColumn(ar, ByVal c)
- Dim br()
- ReDim br(1 To 1)
- For i = 2 To UBound(ar)
- If Len(ar(i, c)) = 0 Then
- Exit For
- Else
- j = j + 1
- ReDim Preserve br(1 To j)
- br(j) = ar(1, c) & ar(i, c)
- End If
- Next
- GetNumofColumn = br
- End Function
- Function CombinM_N(ar0, n0)
- Dim k&, a&(), result(), m0&
- If n0 > 0 Then
- m0 = UBound(ar0)
- k = Application.WorksheetFunction.Combin(m0, n0)
- ReDim result(1 To k, 1 To n0)
- k = 0
- ReDim a(1 To n0)
- Call DG(a, 0, 1, ar0, result, m0, n0, k)
- Else
- ReDim result(0, 0)
- End If
- CombinM_N = result
- End Function
- Sub DG(a&(), i&, t&, ar0, result, m, n, k)
- Dim j&, l&
- For j = i + 1 To m - n + t
- a(t) = j
- If t = n Then
- k = k + 1
- For l = 1 To n
- result(k, l) = ar0(a(l))
- Next
- Else
- Call DG(a, j, t + 1, ar0, result, m, n, k)
- End If
- Next
- End Sub
复制代码
|
评分
-
1
查看全部评分
-
|