martin2k

ForumsVB6GamesSoftwareDirectoryHTMLArticlesBlogContact

How do I generate a list of random numbers, which are all different?


 

Home

Read and add posts to the Visual Basic 6.0 Forums

Download some of my programs and OCXs

Read the Tips here

The old style forum is still available here

Contact


 

Question

From: Martin Allen
Date: 02-01-02 12:39
Subject: Random number problem
Question:

I am trying to make an array that contains random numbers, but each number has to be different.  I am having difficulty in writing the code. Can anyone help?

Dim D(9) As Integer, i As Integer, j As Integer, k As Integer
Do Until i = 9
j = 0
    Do Until j = i
        k = Int((Rnd * 9 - 0 + 1) + 0)
        If D(j) = k Then
            k = Int((Rnd * 9 - 0 + 1) + 0)
        Else
            D(i) = k
            j = j + 1
        End If
    Loop

i = i + 1
Loop

MsgBox D(0) & D(1) & D(2) & D(3) & D(4) & D(5) & D(6) & D(7) & D(8) & D(9)

Reply by colin harman:

is it all u want, random numbers? cos just put  original  x * , if u dont get wat i mean email me

Reply by Vaios:

Dim oColRandom As New Collection

Dim D(9) As Integer
Dim
k As Integer

Do Until oColRandom.Count = 9 'zero based

    k = Int((Rnd * 9 - 0 + 1) + 0)
    lCount = lCount + 1

    On Error Resume Next
    oColRandom.Add k, Chr(k)

Loop

For k = 0 To oColRandom.Count
    D(k) = oColRandom.Item(k)
Next k

MsgBox D(0) & D(1) & D(2) & D(3) & D(4) & D(5) & D(6) & D(7) & D(8) & D(9)

Answer by Martin Allen:

Thanks for that code.  But I already found the answer by downloading this VB project - http://www.vb-helper.com/HowTo/rndlist.zip.

When your code is run, the same sequence of numbers is returned - 0756318492.  Although all numbers are different, the numbers are always in the same order (unless that's a coincidence, which I doubt).  The above project sorts these numbers into a random order.


blog comments powered by Disqus

Archived Comments

From: student
Date: Sunday, December 11, 2005 at 23:54:10
Comments: The numbers are always in the same order is because you need to declare : 
RANDOMIZER TIMER
in the beginning, or else it will always give you the same set of numbers!
 
Reply: The statement you need is: Randomize.

Martin Allen 1999 - 2011.  Last updated Tuesday 09 August 2011 08:15:46 PM +0100.