Question 2x random

wojtek1150

Member
Joined
Sep 14, 2011
Messages
5
Programming Experience
1-3
Hello, :peaceful:I got one problem.I need to generate two different random numbersbut this
VB.NET:
Dim r1 As New RandomDim
 r2 As New Random
l1 = r1.next (0,1000)
l2 = r2.next (0,1000)
give me random numbers, but they are same


any sugestions?
 
This problem can be avoided by creating a single Random object rather than multiple ones.
Quote from help for Random class btw :)
 
Dim randnum As New Random()
Dim r1, r2 As Integer
r1 = randnum.Next(1, 1001)
r2 = randnum.Next(1, 1001)

This will generate 2 random numbers between 1 and 1000. The first argument after Next is the starting number in the range. The second argument must be 1 higher than the upper range.
 
With random numbers there is still a chance that you'll get a duplicate. If it is critical that the two numbers be different, I would suggest that you put in a line or two to check that is the case. For example:

Dim randnum As New Random()
Dim r1, r2 As Integer
r1 = randnum.Next(1, 1001)
Do
r2 = randnum.Next(1, 1001)
Loop until not r1 = r2
 
Back
Top