Reputation: 73
I'm trying to use multiple random variables for something I'm making in Visual Studio. This is the code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Declaring random variables
Dim cC1 As New Random
Dim cC2 As New Random
Dim cC3 As New Random
Dim cC4 As New Random
Dim cC5 As New Random
Dim cCard1 As New Integer
cCard1 = cC1.Next(1, 14)
Dim cCard2 As New Integer
cCard2 = cC2.Next(1, 14)
Dim cCard3 As New Integer
cCard3 = cC3.Next(1, 14)
Dim cCard4 As New Integer
cCard4 = cC4.Next(1, 14)
Dim cCard5 As New Integer
cCard5 = cC5.Next(1, 14)
'Computers random choice
Dim x As New Integer
Dim s As New Random
x = s.Next(1, 14)
There's a bit more but it's basically a duplicate. The issue is that these "random" variables are ALL the same. I thought that the error might have been because the code was like so:
Dim cCard1 = cC1.Next(1, 14)
I have written another program which executes what I wanted with the exact same code, while this programs variables aren't all too random. :(
After changing it to the current code, the issue is still prominent and I'm looking for an explanation to why this occurs, and more importantly, a way to correct this error. Any form of help will be highly appreciated!
Upvotes: 0
Views: 608
Reputation: 354406
That is because when you create the Random
instance, it uses the current time as its seed. The seed is a number that, when identical, yields the exact same sequence of pseudo-random numbers. In your case this happens fast enough that all instances share the same seed and thus all yield the same first number.
You should create one Random
instance and get multiple numbers from it instead.
Upvotes: 3