 • Print
This chapter is from the book

## 7.8 Case Study: Random-Number Generation

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

There’s something in the air of a casino that invigorates people—from the high rollers at the plush mahogany-and-felt craps tables to the quarter poppers at the one-armed bandits. It’s 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 app 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.

#### Secure Random Numbers

According to Microsoft’s documentation for class Random, the random values it produces “are not completely random because a mathematical algorithm is used to select them, but they are sufficiently random for practical purposes.” Such values should not be used, for example, to create randomly selected passwords. If your app requires so-called cryptographically secure random numbers, use class RNGCryptoServiceProvider1 from namespace System.Security.Cryptography) to produce random values:

```https://msdn.microsoft.com/library/system.security.cryptography.
rngcryptoserviceprovider```

### 7.8.1 Creating an Object of Type Random

A new random-number generator object can be created with class Random (from the System namespace) as follows:

`Random randomNumbers = new Random();`

The Random object can then be used to generate random byte, int and double values—we discuss only random int values here.

### 7.8.2 Generating a Random Integer

Consider the following statement:

`int randomValue = randomNumbers.Next();`

When called with no arguments, 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 numbers—a 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 app yields a different sequence of random values.

### 7.8.3 Scaling the Random-Number Range

The range of values produced directly by method Next often differs from the range of values required in a particular C# app. For example, an app that simulates coin tossing might require only 0 for “heads” and 1 for “tails.” An app that simulates the rolling of a six-sided die might require random integers in the range 1–6. 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 1–4. For cases like these, class Random provides versions of method Next that accept arguments. 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); // 0, 1, 2, 3, 4 or 5`

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

### 7.8.4 Shifting Random-Number Range

Suppose we wanted to simulate a six-sided die that has the numbers 1–6 on its faces, not 0–5. 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 value—in this case 1—to the result of method Next, as in

`int face = 1 + randomNumbers.Next(6); // 1, 2, 3, 4, 5 or 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 1–6.

### 7.8.5 Combining Shifting and Scaling

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

`int face = randomNumbers.Next(1, 7); // 1, 2, 3, 4, 5 or 6`

### 7.8.6 Rolling a Six-Sided Die

To demonstrate random numbers, let’s develop an app that simulates 20 rolls of a six-sided die and displays each roll’s value. Figure 7.5 shows two sample outputs, which confirm that the results of the preceding calculation are integers in the range 1–6 and that each run of the app can produce a different sequence of random numbers. Line 9 creates the Random object randomNumbers to produce random values. Line 15 executes 20 times in a loop to roll the die and line 16 displays the value of each roll.

``` 1   // Fig. 7.5: RandomIntegers.cs
2   // Shifted and scaled random integers.
3   using System;
4
5   class RandomIntegers
6   {
7      static void Main()
8      {
9         Random randomNumbers = new Random(); // random-number generator
10
11         // loop 20 times
12         for (int counter = 1; counter <= 20; ++counter)
13         {
14            // pick random integer from 1 to 6
15            int face = randomNumbers.Next(1, 7)
16            Console.Write(\$"{face}  "); // display generated value
17         }
18
19         Console.WriteLine();
20      }
21   }```
`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`

Fig. 7.5 | Shifted and scaled random integers.

#### Rolling a Six-Sided Die 60,000,000 Times

To show that the numbers produced by Next occur with approximately equal likelihood, let’s simulate 60,000,000 rolls of a die (Fig. 7.6). Each integer from 1 to 6 should appear approximately 10,000,000 times.

``` 1   // Fig. 7.6: RollDie.cs
2   // Roll a six-sided die 60,000,000 times.
3   using System;
4
5   class RollDie
6   {
7      static void Main()
8      {
9         Random randomNumbers = new Random(); // random-number generator
10
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
17
18         // summarize results of 60,000,000 rolls of a die
19         for (int roll = 1; roll <= 60000000; ++roll)
20         {
21            int face = randomNumbers.Next(1, 7); // number from 1 to 6
22
23            // determine roll value 1-6 and increment appropriate counter
24            switch (face)
25            {
26               case 1:
27                  ++frequency1; // increment the 1s counter
28                  break;
29               case 2:
30                  ++frequency2; // increment the 2s counter
31                  break;
32               case 3:
33                  ++frequency3; // increment the 3s counter
34                  break;
35               case 4:
36                  ++frequency4; // increment the 4s counter
37                  break;
38               case 5:
39                  ++frequency5; // increment the 5s counter
40                  break;
41               case 6:
42                  ++frequency6; // increment the 6s counter
43                  break;
44            }
45         }
46
48         Console.WriteLine(\$"1\t{frequency1}\n2\t{frequency2}");
49         Console.WriteLine(\$"3\t{frequency3}\n4\t{frequency4}");
50         Console.WriteLine(\$"5\t{frequency5}\n6\t{frequency6}");
51      }
52   }```
```Face    Frequency
1       10006774
2       9993289
3       9993438
4       10006520
5       9998762
6       10001217```
```Face    Frequency
1       10002183
2       9997815
3       9999619
4       10006012
5       9994806
6       9999565```

Fig. 7.6 | Roll a six-sided die 60,000,000 times.

As the two sample outputs show, the values produced by method Next enable the app to realistically simulate rolling a six-sided die. The app 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 19–45) iterates 60,000,000 times. During each iteration, line 21 produces a random value from 1 to 6. This face value is then used as the switch expression (line 24). Based on the face value, the switch statement increments one of the six counter variables during each iteration of the loop. (In Section 8.4.7, we show an elegant way to replace the entire switch statement in this app with a single statement.) The switch statement has no default label because we have a case label for every possible die value that the expression in line 21 can produce. Run the app several times and observe the results. You’ll see that every time you execute this apkp, it produces different results.

### 7.8.7 Scaling and Shifting Random Numbers

Previously, we demonstrated the statement

`int 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 1face < 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

`int 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’s also possible to choose integers at random from sets of values other than ranges of consecutive integers. For this purpose, it’s 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

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

In this case, randomNumbers.Next(5) produces values in the range 0–4. 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

```int 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.8.8 Repeatability for Testing and Debugging

As we mentioned earlier in this section, 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 app to produce a different sequence of random numbers.

When debugging an app, it’s sometimes useful to repeat the same sequence of pseudorandom numbers during each execution of the app. This repeatability enables you to prove that your app is working for a specific sequence of random numbers before you test the app 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 (an int) seeds the random-number calculation—using the same seedValue every time produces the same sequence of random numbers. Different seed values, of course, produce different sequences of random numbers.