|
“没有最好,只有更好”是好多企业的文化理念;而在情感上,如上《非诚勿扰》,往往更易牵手成功;对于程序,偶也是这么认为。彭版的排列组
合(http://club.excelhome.net/viewth ... 1%D0%2B%D7%EE%D3%C5)算法非常巧妙,但是冠以“最优”,让许
多“纠客”内心蠢蠢欲动,想挑出毛病来。下面就让偶做一下论坛“纠客”吧。
1、显式地声明数据类型,尽量不要使用Variant类型,省去类型的转换,可以提高不少效力,也节省内存;
2、一维数组比二维形式速度更快;通过这两步的优化,就算法(不考虑写入文件)约可提高一倍的效率,见Peng2。
3、对于连接字符串,用“&”效率并不高,特别M值比较大时更是降低效率的凶杀,以N=30、M=6和N=30、M=24为例,取得同样的组合数,后者用时是
前者的4倍多,可以考虑用MID句替之;
4、用“Open "d:\peng.txt" For Output As #1”逐个写入虽可以防止内存溢出,但效率也降低,可以考虑把数据先存放在数组(内存允许内的大小
),再分次写入文件。这一步待完善。- Option Base 1
- 'Dim c() As String
- Dim a() As String
- Dim b() As Integer
- Dim n%, m%, Mn&, nL As Byte, S$, Rng As Range
- Public Sub ZhuHe()
- Dim cc, x%, Sl$
- S = ""
- t = Timer
- n = Cells(65536, 1).End(3).Row
- m = [b1]
- ReDim a(n)
- ReDim b(m)
- r = Range("a1:a" & n)
- For Each cc In r
- If Len(cc) > nL Then nL = Len(cc)
- Next
- Sl = String(nL, "0")
- For i = 1 To n
- a(i) = Format(r(i, 1), Sl)
- Next
- Mn = Application.Combin(n, m)
- For i = 1 To m
- b(i) = i
- S = S & " " & a(i)
- Next
- S = Mid(S, 2)
- 'ReDim c(Mn) '数组存放
- For i = 1 To Mn
- ' c(i) = S '数组存放
- SetS m
- Next
- Set Rng = [f65536].End(3)(2, 1)
- Rng(1, 2) = Format(Timer - t, "0.00")
- Rng = Mn
- Rng(1, 0) = "Zamyi"
- 'Dim Fs As FileSystemObject, F As TextStream '写入文件
- 'Set Fs = CreateObject("scripting.filesystemobject")
- 'Set F = Fs.OpenTextFile("d:\Text.txt", 2, True)
- 'F.Write Join(c, vbNewLine)
- 'F.Close
- 'Set F = Nothing
- 'Set Fs = Nothing
- End Sub
- Private Sub SetS(ByVal mm%)
- If b(mm) = n - m + mm Then
- If mm > 1 Then
- SetS mm - 1
- b(mm) = b(mm - 1) + 1
- Mid(S, (nL + 1) * (mm - 1) + 1, nL) = a(b(mm))
- End If
- Else
- b(mm) = b(mm) + 1
- Mid(S, (nL + 1) * (mm - 1) + 1, nL) = a(b(mm))
- End If
- End Sub
复制代码 |
评分
-
3
查看全部评分
-
|