快捷搜索:

递归与组合

福利彩票和体育彩票近两年对照火暴,响应在VB论坛上大年夜家评论争论也较多。着实选择彩票与聚拢选择子集相同事理。下面给出一种VB的递归算法(虽然明知存入数组会加快运算速率,但终极也没能知足地实现,请大年夜家多多指教。别的,效率确凿不高)

Option Explicit

Private Sub Command1_Click()

Dim temp, i As Long, starttime As Long, endtime As Long

starttime = Timer

temp = cmn(22, 6)

endtime = Timer

Open "d:\mofn.txt" For Binary As #1 '写入文件

Put #1, , temp

Close #1

MsgBox UBound(Split(temp, vbCrLf)) + 1 & " 种组合", 64, "共用时 " & endtime - starttime & " 秒" '谋略组合可能环境和耗时

End Sub

Function cmn(ByVal m As Integer, ByVal n As Integer) As String ' select n number from 1~m

Dim a() As String, temp As String, i As Long

ReDim a(1 To m) '定义数组

For i = 1 To m

a(i) = i

Next

If m = 3 Then

If n = 1 Then cmn = 1 & vbCrLf & 2 & vbCrLf & 3

If n = 2 Then cmn = "1,2" & vbCrLf & "1,3" & vbCrLf & "2,3"

If n = 3 Then cmn = "1,2,3"

ElseIf m > 3 Then

If n = 1 Then cmn = Join(a, vbCrLf)

If n = m Then cmn = Join(a, ",")

If n > 1 And n < m Then

temp = cmn(m - 1, n - 1)

'Debug.Print m - 1 & "," & n - 1 & vbCrLf & "----------------" & vbCrLf & temp & vbCrLf & "---------------------------" & vbCrLf '可以在急速窗口查看算法历程

temp = WordStr(temp, vbCrLf, "," & m & vbCrLf) & "," & m

cmn = cmn(m - 1, n) & vbCrLf & temp

End If

End If

End Function

下面给出使用聚拢实现不重复随机拔取某几个号码,这个函数也可用来实现数组整个元素的随机排列。

Function getone(ByVal m As Integer, ByVal n As Integer) As String ' one random option to select n number from 1~m without repeat number

Dim a() As String, temp As New Collection, i As Long, tempi As Long

ReDim a(1 To n) '定义数组

For i = 1 To m

temp.Add i'可以根据必要变动

Next

Randomize

For i = 1 To n

tempi = Int(Rnd * temp.Count) + 1

a(i) = temp(tempi)

temp.Remove tempi

Next

getone = Join(a, ",")

Set temp = Nothing

Erase a

End Function

Private Sub Command2_Click()'演示用法

MsgBox getone(30, 8), 64, "30选8 的一种选法"

MsgBox getone(100, 100), 64, "1 到100 的一种不重复全排列"

End Sub

您可能还会对下面的文章感兴趣: