Generating Random Numbers
Posted
Tue, Aug 11 2009 15:52
by
Deborah Kurata
There are many uses for generating a set of random numbers, especially if you are developing a game. .NET provides a Random class just for this purpose.
To generate a set of 10 random numbers between 1 and 100, you use the Random class as follows:
In C#:
Random rand = new Random();
List<int> randomNumbers = new List<int>();
for (int i = 0; i < 10; i++)
{
randomNumbers.Add(rand.Next(1, 101));
}
randomNumbers.ForEach(i => Debug.WriteLine(i));
In VB:
Dim rand As New Random
Dim randomNumbers As New List(Of Integer)
For i As Integer = 1 To 10
randomNumbers.Add(rand.Next(1, 101))
Next
For Each i As Integer In randomNumbers
Debug.WriteLine(i)
Next
In both examples, the random numbers are generated and added to a list. The contents of the list is then displayed in the debug window.
The Next method of the Random class returns a random number within the defined range, inclusive of the lower bound and exclusive of the upper bound. This means that using Next(1, 101) picks a random number from 1 to 100.
A second overload of the Next method takes only one parameter, which is the upper bound. Using Next(101) picks a random number from 0 to 100.
A third overload of the Next method takes no parameters. Using Next() picks a random number from 0 to the maximum integer value – 1.
Enjoy!