Link to home
Start Free TrialLog in
Avatar of onemorecoke
onemorecoke

asked on

Random numbers in an array in VBScript

In vbscript, I need a function that will fill an array with random numbers but not repeating.  For instance, if I have 9 numbers, the numbers in the array need to be from 1 to 10.  Example:

Trial #1: 4,1,6,3,9,8,2,5,7
Trail #2: 9,3,1,4,5,7,2,6,8
...
ASKER CERTIFIED SOLUTION
Avatar of ltlbearand3
ltlbearand3
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
...or you can just FILL the array with 1 to 10. then SHUFFLE it by swapping random indices.
Interesting puzzle!

Here's my go.  Once it uses a number from 1 to 10, it removes that number so it cannot be chosen again.

Regards,
Daz.
Option Explicit

Dim arrTrial(10), strTrial, dicNums, i, arrNums, iNum

Randomize
Set dicNums = CreateObject("Scripting.Dictionary")

'# Load dictionary with 1 to 10
For i = 1 to 10
    dicNums(i) = i
Next

'# Load arrTrial array with random elements from dictionary, removing the element from the dictionary whenever it is used
Do
    i = dicNums.Count
    arrNums = dicNums.Keys
    iNum = Int(Rnd()*i + 1) - 1
    arrTrial(i - 1) = arrNums(iNum)
    dicNums.Remove(arrNums(iNum))
    If dicNums.Count <1 Then Exit Do
Loop




'#  Test the array

strTrial = Join(arrTrial, " ")

MsgBox "arrTrial = " & strTrial

Open in new window