Something Random is something that doesn't have a particular order.
Sometimes in Programming we need to generate with such data. Visual Basic.NET therefore provides a class defined in the System
namespace called Random
.
This class represents a pseudo-random number generator. This implies that it is will produce a sequence of numbers that meet certain statistical requirements for randomness.
The random class can:
New()
constructor. This will produce a System.Random
instance that is using a time-dependent default seed value.New(Seed As Integer)
constructor. This will produce a System.Random
instance using the specified seed value.The System.Random
class provides us the NextBytes()
method to crete random bytes.
Public Overridable Sub NextBytes(buffer() As Byte)
There is the Next()
method that will return us a non-negative random integer.
This method returns a 32-bit signed integer greater than or equal to 0 and less than System.Int32.MaxValue
.
Next(Integer) As Integer
that returns a random integer that is less than the specified maximum.
Public Overridable Function [Next](maxValue As Integer) As Integer
It receive the maxValue, the upper bound of the random number to be generated. That maxValue must be greater than or equal to 0.
Note that the return value includes 0
but not maxValue
.
Next(Integer,Integer) As Integer
that returns a random number with the specified range.
Public Overridable Function [Next](minValue As Integer, maxValue As Integer) As Integer
You pass the minimum value and maximum value. The minimum value is inclusive while the maximum value is exclusive.
System.Random
also has a NextDouble() As Double
that returns a random floating point number that is greater than or equal to 0.0
and less than 1.0
.
public Overridable Function NextDouble() As Double
Also defined is the Sample() As Double
that returns random double precision floating-point number between 0.0
and 1.0
.
Let's look at an example to generate random intgers and doubles and show them in the console inside a loop.
Imports System
Imports System.Globalization
Module Program
ReadOnly r As Random = New Random()
Private Sub generateRandomIntegers(ByVal min As Integer, ByVal max As Integer)
Console.WriteLine("RANDOM INTEGERS")
For i = 0 To 10 - 1
Console.WriteLine(r.[Next](min, max).ToString())
Next
End Sub
Private Sub generateRandomDoubles()
Console.WriteLine("RANDOM DOUBLES")
For i = 0 To 10 - 1
Console.WriteLine(r.NextDouble().ToString(CultureInfo.InvariantCulture))
Next
End Sub
Sub Main()
generateRandomIntegers(1, 10)
Console.WriteLine()
generateRandomDoubles()
Console.ReadLine()
End Sub
End Module
RESULT:
RANDOM INTEGERS
6
8
5
2
4
6
9
6
5
7
RANDOM DOUBLES
0.0471752514351044
0.257842493363583
0.351131838909877
0.446065263099068
0.341791984318659
0.781808037674896
0.213321405096595
0.0824347027030004
0.965635905026289
0.147332565461906