|
8#
楼主 |
发表于 2009-10-29 11:06:06
|
只看该作者
这样网址打不开,我还是把代码发上来
如何产生不重复的随机数?
先创建个类模块:Random
类模块代码如下:
Dim c As Collection
'初始化,定义产生随机数的最小值和最大值
Public Sub Init(min As Integer, max As Integer)
Set c = New Collection
Dim i As Integer
For i = min To max
c.Add i
Next
End Sub
'产生不重复的随机数
Public Function RandomNext() As Integer
Dim i As Integer
Dim number As Integer, upperbound As Integer
upperbound = c.Count
If upperbound > 0 Then
number = Int((upperbound) * Rnd + 1)
RandomNext = CInt(c.Item(number))
c.Remove (number)
Else
RandomNext = 0
End If
End Function
Private Sub Class_Terminate()
Set c = Nothing
End Sub
测试:
Dim r As New Random
Sub Test() '请先运行Init
Dim i As Integer
For i = 0 To 10
Debug.Print r.RandomNext
Next
End Sub
Sub Init()
r.Init 1, 100
End Sub
这里使用集合来实现的,也可以用哈希表来做,道理差不多。哈希表需要自己定义类模块。 |
|