So you write a section of code like the following.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Randomize() x = Math.Floor(Rnd() * 6) + 1 End Sub
But when you run it, it only returns the same number.
The .net framework provides you with a solution.
Dim MyRandomNumber As New Random()
I personally like using
Dim MyRandomNumber As New Random(Now.Milliseconds)
Why the Now.Milliseconds?
By using Now.Milliseconds as the seed for the Random Number Generator, makes it less likely that the sequence of numbers will be repeated.
Now after you defined your Random Number Generator (MyRandomNumber) you'll want to be able to utilize it.
There different ways of getting a random number out it.
A Random Integer (Positive Only)
Dim x As Integer x=MyRandomNumber.Next
A Random Integer 0 - ?
Dim x As Integer x=MyRandomNumber.Next(10)
The numbers are from 0 up to but not including 10
[b]A Random Integer From A up to B
Dim x As Integer x=MyRandomNumber.Next(65, 91)
In this case between 65 & 90 inclusive.
In the case of Double it's a little different.
You can only have a random double which has a value between 0 and 1.
Dim x As Double x=MyRandomNumber.NextDouble
What if you want a random double between 0 and 100 (inclusive)?
Treat the value of the random double as if it was a percentage of some other value. Example
Dim x As Double x==MyRandomNumber.NextDouble * 100
For a in-between value it not so easy. So I create a Function to do it for you.
Private Function RandomDouble_Between(ByRef RnG As Random,ByVal FromValue As Double, ByVal ToValue As Double) As Double If RnG Is Nothing Then Return Double.NaN If FromValue>ToValue Then Return Double.NaN Dim Delta As Double = ToValue - FromValue Return (RnG.NextDouble * Delta) + FromValue End Function
Dim x As Double x=RandomDouble_Between(MyRandomNumber, 65,91)
You may have notice that the a Random Number Generator has the follow method .Bytes and wonder what it does.
It makes it easy to generate an array full of random bytes.
Dim TheArray(9) As Byte MyRandomNumber.NextBytes(TheArray)
I hope you find the contents of this tutorial useful.