Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Random Number Generation - JavaScript(JS)

Chapter: Internet & World Wide Web HOW TO PROGRAM - The Ajax Client - JavaScript: Functions

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Random Number Generation - JavaScript(JS)

We now take a brief and, it is hoped, entertaining diversion into a popular programming application, namely simulation and game playing.

Random Number Generation

 

We now take a brief and, it is hoped, entertaining diversion into a popular programming application, namely simulation and game playing. In this section and the next, we develop a nicely structured game-playing program that includes multiple functions. The program uses most of the control structures we have studied.

 

There is something in the air of a gambling 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 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 through the Math object’s random method. (Remember, we are calling random a method because it belongs to the Math object.)

Consider the following statement:

 

var randomValue = Math.random();

 

Method random generates a floating-point value from 0.0 up to, but not including, 1.0. If random truly produces values at random, then every value from 0.0 up to, but not includ-ing, 1.0 has an equal chance (or probability) of being chosen each time random is called.

 

The range of values produced directly by random is often different than what is needed in a specific application. For example, a program that simulates coin tossing might require only 0 for heads and 1 for tails. A program that simulates rolling a six-sided die would require random integers in the range from 1 to 6. A program that randomly predicts the next type of spaceship, out of four possibilities, that will fly across the horizon in a video game might require random integers in the range 0–3 or 1–4.

 

To demonstrate method random, let us develop a program (Fig. 9.4) that simulates 20 rolls of a six-sided die and displays the value of each roll. We use the multiplication oper-ator (*) with random as follows:

 

Math.floor( 1 + Math.random() * 6 )

 

First, the preceding expression multiplies the result of a call to Math.random() by 6 to pro-duce a number in the range 0.0 up to, but not including, 6.0. This is called scaling the range of the random numbers. Next, we add 1 to the result to shift the range of numbers to produce a number in the range 1.0 up to, but not including, 7.0. Finally, we use method Math.floor to round the result down to the closest integer not greater than the argument’s value—for example, 1.75 is rounded to 1. Figure 9.4 confirms that the results are in the range 1 to 6.

 

      <?xml version = "1.0" encoding = "utf-8"?>

 

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

      <!-- Fig. 9.4: RandomInt.html -->

 

      <!-- Random integers, shifting and scaling. -->

 

      <html xmlns = "http://www.w3.org/1999/xhtml">

 

      <head>

 

      <title>Shifted and Scaled Random Integers</title>

 

        <style type = "text/css">

 

table { width: 50%;

border: 1px    solid gray;

text-align:       center }

        </style>

 

        <script type = "text/javascript">

        <!--

 

        var value;

        document.writeln( "<table>" );

 

        document.writeln( "<caption>Random Numbers</caption><tr>" );

 

        for ( var i = 1; i <= 20; i++ )

{

            value = Math.floor( 1 + Math.random() * 6 );       

document.writeln( "<td>" + value + "</td>" );

                       

// start a new table row every 5 entries

if ( i % 5 == 0 && i != 20 )

            document.writeln( "</tr><tr>" );

} // end for

                       

document.writeln( "</tr></table>" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run the script again</p>

 

      </body>

 

</html>


 

Fig. 9.4 | Random integers, shifting and scaling.

 

To show that these numbers occur with approximately equal likelihood, let us simu-late 6000 rolls of a die with the program in Fig. 9.5. Each integer from 1 to 6 should appear approximately 1000 times. Use your browser’s Refresh (or Reload) button to exe-cute the script again.

 

    <?xml version = "1.0" encoding = "utf-8"?>

 

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

 

    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

 

    <!-- Fig. 9.5: RollDie.html -->

 

    <!-- Rolling a Six-Sided Die 6000 times. -->

 

<html xmlns = "http://www.w3.org/1999/xhtml">

      <head>

 

      <title>Roll a Six-Sided Die 6000 Times</title>

 

        <script type = "text/javascript">

        <!--

 

        var frequency1 = 0;

 

        var frequency2 = 0;

 

        var frequency3 = 0;

 

        var frequency4 = 0;

 

        var frequency5 = 0;

 

        var frequency6 = 0;

 

        var face;

        // roll die 6000 times and accumulate results

 

        for ( var roll = 1; roll <= 6000; roll++ )

{

face = Math.floor( 1 + Math.random() * 6 );

 

switch ( face )

{

case 1:

++frequency1;

break;

case 2:

++frequency2;

break;

case 3:

++frequency3;

break;

case 4:

++frequency4;

break;

case 5:

++frequency5;

break;

case 6:

++frequency6;

break;

        } // end switch

 

        } // end for

        document.writeln( "<table border = \"1\">" );

 

        document.writeln( "<thead><th>Face</th>" +

        "<th>Frequency</th></thead>" );

 

        document.writeln( "<tbody><tr><td>1</td><td>" +

        frequency1 + "</td></tr>" );

 

        document.writeln( "<tr><td>2</td><td>" + frequency2 +

        "</td></tr>" );

 

        document.writeln( "<tr><td>3</td><td>" + frequency3 +

        "</td></tr>" );

 

        document.writeln( "<tr><td>4</td><td>" + frequency4 +

        "</td></tr>" );

 

        document.writeln( "<tr><td>5</td><td>" + frequency5 +

        "</td></tr>" );

document.writeln( "<tr><td>6</td><td>" + frequency6 +

      "</td></tr></tbody></table>" );

      // -->

 

      </script>

 

      </head>

 

      <body>

 

      <p>Click Refresh (or Reload) to run the script again</p>

 

      </body>

 

</html>


Fig. 9.5 | Rolling a six-sided die 6000 times.

As the output of the program shows, we used Math method random and the scaling and shifting techniques of the previous example to simulate the rolling of a six-sided die. Note that we used nested control structures to determine the number of times each side of the six-sided die occurred. Lines 12–17 declare and initialize counter variables to keep track of the number of times each of the six die values appears. Line 18 declares a variable to store the face value of the die. The for statement in lines 21–46 iterates 6000 times. During each iteration of the loop, line 23 produces a value from 1 to 6, which is stored in face. The nested switch statement in lines 25–45 uses the face value that was randomly chosen as its controlling expression. Based on the value of face, the program increments one of the six counter variables during each iteration of the loop. Note that no default case is provided in this switch statement, because the statement in line 23 produces only the values 1, 2, 3, 4, 5 and 6. In this example, the default case would never execute. After we study Arrays in Chapter 10, we discuss a way to replace the entire switch statement in this program with a single-line statement.

 

Run the program several times, and observe the results. Note that the program pro-duces different random numbers each time the script executes, so the results should vary.

The values returned by random are always in the range

 

0.0 Math.random() < 1.0

 

Previously, we demonstrated the statement

 

face = Math.floor( 1 + Math.random() * 6 );

 

which simulates the rolling of a six-sided die. This statement always assigns an integer (at random) to variable face, in the range 1 face 6. Note that 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 number used to scale random with the multiplication operator (6 in the preceding statement) and that the starting number of the range is equal to the number (1 in the pre-ceding statement) added to Math.random() * 6. We can generalize this result as

 

face = Math.floor( a + Math.random() * b );

 

where a is the shifting value (which is equal to the first number in the desired range of consecutive integers) and b is the scaling factor (which is equal to the width of the desired range of consecutive integers). In this chapter’s exercises, you’ll see that it’s possible to choose integers at random from sets of values other than ranges of consecutive integers.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail


Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.