现有从1到100 的一排数.想随机产生20个不重复的数.
如  1,2,3,4,5,6,7,8..................................97,98,99,100   共100个数
随机产生的20个数为
1,5,8,9,10,23,56,78,80........99不知能不能实现,
如能实现,希望各位达人.给出个思路或完整的代码
小弟不胜感谢!

解决方案 »

  1.   

    如果对产生数的概率没什么要求的话
    可以用rand()产生,然后判断前面产生的,如果已有,重新产生,没有就把这个数加入(这样产生的数的概率有变化)
      

  2.   

    Private Sub Command1_Click()
    getarray 20
     End SubSub getarray(ByVal n As Integer, Optional ByRef result As String)
    Dim a() As String, i As Integer, j As Integer, temp As String
    ReDim a(1 To 100)
    For i = 1 To 100
    a(i) = i
    Next
    Randomize
    For i = 1 To n
    j = Int(i + Rnd * (101 - i))
    temp = a(j)
    a(j) = a(i)
    a(i) = temp
    Next
    ReDim Preserve a(1 To n)
    result = Join(a, ",")
    Erase a
    MsgBox result, vbInformation, n & "个1-100 间的不重复随机数"
    End Sub
      

  3.   

    或者直接用字符串:Private Sub Command1_Click()
    getarray 20
     End SubSub getarray(ByVal n As Integer, Optional ByRef result As String)
    Dim x As String, y As String, temp As String, i As Integer
    For i = 1 To 100
    x = x & " " & Right("000" & i, 3)
    Next
    Randomize
    For i = 1 To 20
    temp = Mid(x, Int(Rnd * (Len(x) \ 4)) * 4 + 1, 4)
    y = y & " " & Val(Trim(temp))
    x = Replace(x, temp, "")
    Next
    MsgBox Trim(y), vbInformation, n & "¸ö1-100 ¼äµÄ²»Öظ´Ëæ»úÊý"
    End Sub
      

  4.   

    Private Sub Command2_Click()
        Dim i As String
        Randomize
        For j = 1 To 20
            
            s = Int(Rnd * (100) + 1) & ","
            i = i & s    Next j
        MsgBox i, vbInformation
    End Sub如果不用数组交换值,这样有时会产生一样的,那这边加Randomize有何用处哦??
    如果楼上的方法把Randomize去掉,似乎也不产生一样的随机数!!怎么理解Randomize?
      

  5.   

    计算机产生的随机数叫伪随机数,和开始的种子数值有关,Randomize就是用时钟发生器的当前数据作种子来产生后续的随机数列,这样一来你每次启动程序得到相同序列的机会就很少,基本达到随机的效果了。
      

  6.   

    回复:加Randomize并不能有效防止随机数的重复出现。Randomize [number]
    Randomize 用 number 将 Rnd 函数的随机数生成器初始化,该随机数生成器给一个新的种子值。如果省略 number,则用系统计时器返回的值作为新的种子值。如果没有使用 Randomize,则 Rnd 函数使用第一次调用 Rnd 函数的种子值。
      

  7.   

    Private Function RandomNumber(lMin As Long, lMax As Long, lCount As Long) As Long()
        Dim n() As Long, i As Long, j As Long, q As Long, r() As Long
        On Error GoTo Err
        If lMax - lMin <= lCount - 1 Then
            ReDim r(lMin To lMax)
            For i = lMin To lMax
                r(i) = i
            Next
        Else
            ReDim r(j To lCount - 1)
            ReDim n(lMin To lMax)
            While j < lCount
                q = Int(Rnd(1) * (lMax - 1) + 1)
                If q >= lMin And q <= lMax Then
                    If n(q) = 0 Then
                        n(q) = 1
                        j = j + 1
                        r(j - 1) = q
    '                    Debug.Print q
                    End If
                    
                End If
                DoEvents
            Wend
        End If
    Err:
        RandomNumber = r
    End Function