Home > Articles

Methods: A Deeper Look

This chapter is from the book

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
47         Console.WriteLine("Face\tFrequency"); // output headers
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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020