本帖最后由 一把小刀闯天下 于 2020-2-20 13:38 编辑
'我的结果怎么会超10^6的,计时不包括输出<2s
'如果需要全部结果那就输出到文本文件吧
'----------------
'修改了一下,单个数处理有点问题。总组合数:3635489,只输出了10^6个组合,,,
Option Explicit
Sub test()
Dim arr, i As Long, j As Long, m As Long, key, t1, t2, dt As Single
dt = Timer
arr = Range("a2:c" & [a2].End(xlDown).Row)
ReDim dic(UBound(arr, 2))
For i = 1 To 3 Step 2
Set dic(i) = CreateObject("scripting.dictionary")
Call comb(arr, i, dic)
Next
Debug.Print dic(3).Count
If dic(3).Count Then
ReDim arr(1 To 10 ^ 6, 1 To 3)
For Each key In dic(3).keys
t1 = Split(dic(1)(key), "|"): t2 = Split(dic(3)(key), "|")
For i = 1 To UBound(t1)
For j = 1 To UBound(t2)
m = m + 1: arr(m, 3) = key
arr(m, 1) = Mid(t1(i), 2): arr(m, 2) = Mid(t2(j), 2)
If m = UBound(arr, 1) Then
Debug.Print Timer - dt
[n1].Resize(m, 3) = arr
Debug.Print Timer - dt
Exit Sub
End If
Next
Next
Next
End If
End Sub
Function comb(arr, p As Long, dic)
Dim i As Long, j As Long, n As Long
ReDim brr(1 To 2 ^ UBound(arr, 1), 1 To 2)
brr(2, 1) = "+" & arr(1, p): brr(2, 2) = arr(1, p)
If p = 1 Then
dic(1)(brr(2, 2)) = "|" & brr(2, 1)
Else
If dic(1).exists(brr(2, 2)) Then dic(p)(brr(2, 2)) = "|" & brr(2, 1)
End If
n = 2
For i = 2 To UBound(arr, 1)
For j = n + 1 To 2 * n
brr(j, 1) = brr(j - n, 1) & "+" & arr(i, p)
brr(j, 2) = brr(j - n, 2) + arr(i, p)
If p = 1 Then
dic(p)(brr(j, 2)) = dic(p)(brr(j, 2)) & "|" & brr(j, 1)
Else
If dic(1).exists(brr(j, 2)) Then dic(p)(brr(j, 2)) = dic(p)(brr(j, 2)) & "|" & brr(j, 1)
End If
Next
n = n * 2
Next
' Range("k1").Offset(, p).Resize(UBound(brr, 1), 2) = brr
End Function
|