Case Study: Random-Number Generation

Case Study Random Number Generation

In this and the next section, we develop a nicely structured game-playing application with multiple methods. The application uses most of the control statements presented thus far in the book and introduces several new programming concepts.

There is something in the air of a casino that invigorates peoplefrom the high rollers at the plush mahogany-and-felt craps tables to the quarter poppers at the one-armed bandits. It is the element of chance, the possibility that luck will convert a pocketful of money into a mountain of wealth. The element of chance can be introduced in an application via an object of class Random (of namespace System). Objects of class Random can produce random byte, int and double values. In the next several examples, we use objects of class Random to produce random numbers.

A new random-number generator object can be created as follows:

Random randomNumbers = new Random();

The random-number generator object can then be used to generate random byte, int and double valueswe discuss only random int values here. For more information on the Random class, see

Consider the following statement:

int randomValue = randomNumbers.Next();

Method Next of class Random generates a random int value in the range 0 to +2,147,483,646, inclusive. If the Next method truly produces values at random, then every value in that range should have an equal chance (or probability) of being chosen each time method Next is called. The values returned by Next are actually pseudorandom numbersa sequence of values produced by a complex mathematical calculation. The calculation uses the current time of day (which, of course, changes constantly) to seed the random-number generator such that each execution of an application yields a different sequence of random values.

The range of values produced directly by method Next often differs from the range of values required in a particular C# application. For example, an application that simulates coin tossing might require only 0 for "heads" and 1 for "tails." An application that simulates the rolling of a six-sided die might require random integers in the range 16. A video game that randomly predicts the next type of spaceship (out of four possibilities) that will fly across the horizon might require random integers in the range 14. For cases like these, class Random provides other versions of method Next. One receives an int argument and returns a value from 0 up to, but not including, the argument's value. For example, you might use the statement

int randomValue = randomNumbers.Next( 6 );

which returns 0, 1, 2, 3, 4 or 5. The argument 6called the scaling factorrepresents the number of unique values that Next should produce (in this case, six0, 1, 2, 3, 4 and 5). This manipulation is called scaling the range of values produced by Random method Next.

Suppose we wanted to simulate a six-sided die that has the numbers 16 on its faces, not 05. Scaling the range of values alone is not enough. So we shift the range of numbers produced. We could do this by adding a shifting valuein this case 1to the result of method Next, as in

face = 1 + randomNumbers.Next( 6 );

The shifting value (1) specifies the first value in the desired set of random integers. The preceding statement assigns to face a random integer in the range 16.

The third alternative of method Next provides a more intuitive way to express both shifting and scaling. This method receives two int arguments and returns a value from the first argument's value up to, but not including, the second argument's value. We could use this method to write a statement equivalent to our previous statement, as in

face = randomNumbers.Next( 1, 7 );


Rolling a Six-Sided Die

To demonstrate random numbers, let's develop an application that simulates 20 rolls of a six-sided die and displays each roll's value. Figure 7.7 shows two sample outputs, which confirm that the results of the preceding calculation are integers in the range 16 and that each run of the application can produce a different sequence of random numbers. The using directive in line 3 enables us to use class Random without fully qualifying its name. Line 9 creates the Random object randomNumbers to produce random values. Line 16 executes 20 times in a loop to roll the die. The if statement (lines 2122) in the loop starts a new line of output after every five numbers, so the results can be presented on multiple lines.

Figure 7.7. Shifted and scaled random integers.

 1 // Fig. 7.7: RandomIntegers.cs
 2 // Shifted and scaled random integers.
 3 using System;
 5 public class RandomIntegers
 6 {
 7 public static void Main( string[] args )
 8 {
 9 Random randomNumbers = new Random(); // random number generator
10 int face; // stores each random integer generated
12 // loop 20 times
13 for ( int counter = 1; counter <= 20; counter++ )
14 {
15 // pick random integer from 1 to 6
16 face = randomNumbers.Next( 1, 7 );
18 Console.Write( "{0} ", face ); // display generated value
20 // if counter is divisible by 5, start a new line of output
21 if ( counter % 5 == 0 )
22 Console.WriteLine();
23 } // end for
24 } // end Main
25 } // end class RandomIntegers
3 3 3 1 1
2 1 2 4 2
2 3 6 2 5
3 4 6 6 1
6 2 5 1 3
5 2 1 6 5
4 1 6 1 3
3 1 4 3 4

Rolling a Six-Sided Die 6000 Times

To show that the numbers produced by Next occur with approximately equal likelihood, let us simulate 6000 rolls of a die (Fig. 7.8). Each integer from 1 to 6 should appear approximately 1000 times.

Figure 7.8. Roll a six-sided die 6000 times.

 1 // Fig. 7.8: RollDie.cs
 2 // Roll a six-sided die 6000 times.
 3 using System;
 5 public class RollDie
 6 {
 7 public static void Main( string[] args )
 8 {
 9 Random randomNumbers = new Random(); // random number generator
11 int frequency1 = 0; // count of 1s rolled
12 int frequency2 = 0; // count of 2s rolled
13 int frequency3 = 0; // count of 3s rolled
14 int frequency4 = 0; // count of 4s rolled
15 int frequency5 = 0; // count of 5s rolled
16 int frequency6 = 0; // count of 6s rolled
18 int face; // stores most recently rolled value
20 // summarize results of 6000 rolls of a die
21 for ( int roll = 1; roll <= 6000; roll++ )
22 {
23 face = randomNumbers.Next( 1, 7 ); // number from 1 to 6
25 // determine roll value 1-6 and increment appropriate counter 26 switch ( face ) 27 { 28 case 1: 29 frequency1++; // increment the 1s counter 30 break; 31 case 2: 32 frequency2++; // increment the 2s counter 33 break; 34 case 3: 35 frequency3++; // increment the 3s counter 36 break; 37 case 4: 38 frequency4++; // increment the 4s counter 39 break; 40 case 5: 41 frequency5++; // increment the 5s counter 42 break; 43 case 6: 44 frequency6++; // increment the 6s counter 45 break; 46 } // end switch 47 } // end for 48 49 Console.WriteLine( "Face Frequency" ); // output headers 50 Console.WriteLine( "1 {0} 2 {1} 3 {2} 4 {3} 5 {4} 6 {5}", 51 frequency1, frequency2, frequency3, frequency4, 52 frequency5, frequency6 ); 53 } // end Main 54 } // end class RollDie
Face Frequency
1 1039
2 994
3 991
4 970
5 978
6 1028
Face Frequency
1 985
2 985
3 1001
4 1017
5 1002
6 1010

As the two sample outputs show, the values produced by method Next enable the application to realistically simulate rolling a six-sided die. The application uses nested control statements (the switch is nested inside the for) to determine the number of times each side of the die occurred. The for statement (lines 2147) iterates 6000 times. During each iteration, line 23 produces a random value from 1 to 6. This face value is then used as the switch expression (line 26) in the switch statement (lines 2646). Based on the face value, the switch statement increments one of the six counter variables during each iteration of the loop. (In Chapter 8, Arrays, we show an elegant way to replace the entire switch statement in this application with a single statement.) Note that the switch statement has no default label because we have a case label for every possible die value that the expression in line 23 can produce. Run the application several times and observe the results. You'll see that every time you execute this application, it produces different results.

7.9.1. Scaling and Shifting Random Numbers

Previously, we demonstrated the statement

face = randomNumbers.Next( 1, 7 );

which simulates the rolling of a six-sided die. This statement always assigns to variable face an integer in the range 1 images/U2264.jpg border=0> face < 7. The width of this range (i.e., the number of consecutive integers in the range) is 6, and the starting number in the range is 1. Referring to the preceding statement, we see that the width of the range is determined by the difference between the two integers passed to Random method Next, and the starting number of the range is the value of the first argument. We can generalize this result as

number = randomNumbers.Next( shiftingValue, shiftingValue + scalingFactor );

where shiftingValue specifies the first number in the desired range of consecutive integers and scalingFactor specifies how many numbers are in the range.

It is also possible to choose integers at random from sets of values other than ranges of consecutive integers. For this purpose, it is simpler to use the version of the Next method that takes only one argument. For example, to obtain a random value from the sequence 2, 5, 8, 11 and 14, you could use the statement

number = 2 + 3 * randomNumbers.Next( 5 );

In this case, randomNumberGenerator.Next( 5 ) produces values in the range 04. Each value produced is multiplied by 3 to produce a number in the sequence 0, 3, 6, 9 and 12. We then add 2 to that value to shift the range of values and obtain a value from the sequence 2, 5, 8, 11 and 14. We can generalize this result as

number = shiftingValue +
 differenceBetweenValues * randomNumbers.Next( scalingFactor );

where shiftingValue specifies the first number in the desired range of values, difference-BetweenValues represents the difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range.

7.9.2. Random-Number Repeatability for Testing and Debugging

As we mentioned earlier in Section 7.9, the methods of class Random actually generate pseudorandom numbers based on complex mathematical calculations. Repeatedly calling any of Random's methods produces a sequence of numbers that appears to be random. The calculation that produces the pseudorandom numbers uses the time of day as a seed value to change the sequence's starting point. Each new Random object seeds itself with a value based on the computer system's clock at the time the object is created, enabling each execution of an application to produce a different sequence of random numbers.

When debugging an application, it is sometimes useful to repeat the exact same sequence of pseudorandom numbers during each execution of the application. This repeatability enables you to prove that your application is working for a specific sequence of random numbers before you test the application with different sequences of random numbers. When repeatability is important, you can create a Random object as follows:

Random randomNumbers = new Random( seedValue );

The seedValue argument (type int) seeds the random-number calculation. If the same seedValue is used every time, the Random object produces the same sequence of random numbers.

Error Prevention Tip 7 2

While an application is under development, create the Random object with a specific seed value to produce a repeatable sequence of random numbers each time the application executes. If a logic error occurs, fix the error and test the application again with the same seed valuethis allows you to reconstruct the same sequence of random numbers that caused the error. Once the logic errors have been removed, create the Random object without using a seed value, causing the Random object to generate a new sequence of random numbers each time the application executes.

Case Study A Game of Chance (Introducing Enumerations)



    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look


    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2


    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures



    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types


    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: