Flylib.com

Books Software

 
 
 

2.3 Generate a Random Number


2.3 Generate a Random Number

Problem

You want to create a statistically random number quickly.

Solution

Create an instance of the System.Random class, and call the Next or NextDouble method.

Discussion

The Random class uses a pseudorandom number generator, which means that it uses an algorithm to generate numbers that are statistically random when viewed in sequence.

To use the Random class, you simply create an instance and call either Next or NextDouble . NextDouble returns a double-precision floating-point number greater than or equal to 0.0, and less than 1.0. Next generates an integer within the maximum and minimum range you specify.

Dim RandomGenerator As New Random() ' Retrieve a random fraction number from 0.0 to 1.0. Dim RandomDouble As Double = RandomGenerator.NextDouble() ' Retrieve a random integer number from 1 to 6. Dim RandomInt As Integer = RandomGenerator.Next(1, 7) ' Retrieve another random integer from 1 to 6. RandomInt = RandomGenerator.Next(1, 7)

Notice that the maximum bound for the Next method is always one higher than the maximum integer in your range.

The Random class is ideal when you need to generate a quick random value for a game, simulation, or test. However, it's not suitable for use with cryptography, because an attacker can guess the "random" number you will generate by examining previous random values and determining how you are seeding the random generator. If you need cryptographically secure random numbers, you can use the System.Security.Cryptography.RNGCryptoServiceProvider class, which is described in Chapter 18 (see recipe 18.15). However, this class is much slower than Random , which will become noticeable if you need to generate thousands of random numbers rapidly .

Note 

By default, the Random class is seeded using the current date and time when you create it. After that, it continues down a "list" of random values. However, if you create two instances of the Random class at exactly the same millisecond (which is quite possible on fast computers), they will be both positioned at the same location in the list, and they will generate the same sequence of "random" numbers! To avoid this problem, only use one Random number generator and retain it for the life of your application. Always avoid code that creates more than one Random object in close succession, like this:

' Because this loop executes so quickly, it's easy to create two ' Random objects with the same seed and end up with ' short sequences of identical numbers (like 8888333322). Dim i As Integer For i = 0 To 10 Dim RandomGenerator As New Random() Console.WriteLine(RandomGenerator.Next(1, 7)) Next



2.4 Work with Non–Base 10 Number Systems

Problem

You want to convert a base 10 number to a hexadecimal, octal, or binary number (or vice versa).

Solution

Use the overloaded Convert.ToString and Convert.ToInt32 shared methods that accept a number indicating the base.

Discussion

Although you can't work directly with non–base 10 numbers in Visual Basic .NET, you can easily convert base 10 values into a string representation that uses a base 2 (binary), base 8 (octal), base 10, or base 16 (hexadecimal). To do so, you use the overloaded Convert.ToString method that accepts two parameters: the base 10 number and the base that should be used for the converted number (which must be 2, 8, 10, or 16).

Dim Number As Integer = 3023 Console.WriteLine("Binary: " & Convert.ToString(Number, 2)) Console.WriteLine("Octal: " & Convert.ToString(Number, 8)) Console.WriteLine("Hexadecimal: " & Convert.ToString(Number, 16))

The output for this code is:

Binary: 101111001111 Octal: 5717 Hexadecimal: bcf

You can also use the shared Convert.ToInt32 , Convert.ToInt16 , or Convert.ToInt64 methods to convert a non–base 10 number from a string into an integer type:

Dim Binary As String = "01" Dim Number As Integer = Convert.ToInt32(Binary, 2) ' Double the number. Number *= 2 ' Convert it back to binary. Binary = Convert.ToString(Number, 2) ' Binary is now "10".

If you need to perform calculations with non–base 10 numbers, you have two choices. You could use the ToInt32 number to convert your numbers to decimal, perform the calculation, and then use ToString to convert the number back into its native representation, as shown above. Alternatively, you could create a custom class that represents the number and provides dedicated methods such as Add , Subtract , Multiply , and so on, which perform native calculations. Recipes 2.5 and 2.6 show similar techniques with classes that represent complex numbers and vectors.