Solved

Random numbers in an array in VBScript

Posted on 2010-11-10
1,050 Views
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
...
0
Question by:onemorecoke

LVL 20

Accepted Solution

ltlbearand3 earned 500 total points
ID: 34107603
I would use the dictionary object so that you can check if the number has already been added to the array.  Here is some sample code for you.  Now a slight warning - this is based of a random number generator.  It could "get stuck" running in the loop until it randomly generates a missing number.

``````Option Explicit

Dim dicNum, i, blnAdded, intNum, myvalue, strMsg

Set dicNum = CreateObject("Scripting.Dictionary")

For i = 0 to 9

intNum = Cint(Rnd()*10)

intNum = Cint(Rnd()*10)

If not dicNum.Exists(intNum) Then

End If

Loop

Next

For each myvalue in dicNum.Items

strMsg = strMsg & " : " & myvalue

Next

msgbox strMsg
``````
0

LVL 85

Expert Comment

ID: 34107920
...or you can just FILL the array with 1 to 10. then SHUFFLE it by swapping random indices.
0

LVL 12

Expert Comment

ID: 34110566
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
``````
0

Featured Post

Hello again, all.  For those of you that have been following along, you'll know that this is my third article on this topic (though it is not Part III).  This article is sort of remedial, and probably the topic with which I should have started the s…
Introduction During my participation as a VBScript contributor at Experts Exchange, one of the most common questions I come across is this: "I have a script that runs against only one computer. How can I make it run against a list of computers in …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…