How do I create an array with random numbers?

2019-03-01 06:53发布

问题:

I'm new at this. I want to create an array of 16 elements. Let's say that my array is ReDim arr(15) as Integer and in that array I want to put the numbers from 1 to 16 but scrambled, for example arr(0) = 3, arr(5) = 8 and so on.

回答1:

Give this a try:

Sub MAIN()
   Dim ary(1 To 16) As Variant
   Dim i As Long, msg As String

   For i = 1 To 16
      ary(i) = i
   Next i

   Call Shuffle(ary)

   msg = ""
   For i = 1 To 16
      msg = msg & vbCrLf & ary(i)
   Next i
   MsgBox msg
End Sub

Sub Shuffle(InOut() As Variant)
    Dim HowMany As Long, i As Long, J As Long
    Dim tempF As Double, temp As Variant

    Hi = UBound(InOut)
    Low = LBound(InOut)
    ReDim Helper(Low To Hi) As Double
    Randomize

    For i = Low To Hi
        Helper(i) = Rnd
    Next i


    J = (Hi - Low + 1) \ 2
    Do While J > 0
        For i = Low To Hi - J
          If Helper(i) > Helper(i + J) Then
            tempF = Helper(i)
            Helper(i) = Helper(i + J)
            Helper(i + J) = tempF
            temp = InOut(i)
            InOut(i) = InOut(i + J)
            InOut(i + J) = temp
          End If
        Next i
        For i = Hi - J To Low Step -1
          If Helper(i) > Helper(i + J) Then
            tempF = Helper(i)
            Helper(i) = Helper(i + J)
            Helper(i + J) = tempF
            temp = InOut(i)
            InOut(i) = InOut(i + J)
            InOut(i + J) = temp
          End If
        Next i
        J = J \ 2
    Loop
End Sub



回答2:

Here is some very lazy code:

Dim arr(15) As Integer
Dim i As Integer, j As Integer
i = 1
Do
    j = Int(16 * Rnd)
    If arr(j) = 0 Then
        arr(j) = i
        i = i + 1
    End If
Loop Until i = 17

Rnd generates a single from 0 to 1, multiply that by 16 and strip the decimal portion with Int and it will give you a random number from 0 to 15.

It isn't efficient, I wouldn't use this in production, but it'll do the job.

Hope this helps!