Coding Random Behavior

By Terry Hawthorne
Director of Technology
Smyth County Public Schools

A text editor is a program that enables you to edit plain text. Unlike a word processor, a text editor does not have the ability to format text in different sizes or styles. A text editor's primary purpose is to edit programming code. If you have a Windows computer, you can use the included Notepad program, but I recommend you download the free Notepad++ or Notetab Lite programs, which are much more capable. OS X computers come with a text editor called TextEdit. Caret is a good choice for Chromebooks. If you using a Linux computer, chances are you already know about text editors.

Most programming languages have the ability to generate a random number. This tutorial focuses on Javascript, which is a good language for beginners. You can code Javascript using a text editor, and view the results in a web browser, such as Chrome.

Javascript includes a Math object that has a number of methods. (Don't worry too much right now if you don't understand what an object or a method is. For the purposes of this tutorial, you can assume that the Math object's methods are like built-in functions.)

You can access any of the Math object's methods with this syntax: Math.methodName(); for example:

var randomNumber = Math.random();

The Math.random() method generates a random decimal number between 0 (inclusive) and 1 (exclusive), as you can see when you click the "Display a random number" button. What if you to generate whole random numbers, say between 0 and 10? You could multiply Math.random() by 10:

var randomNumber = Math.random() * 10;

The Javascript Math object also has a round method: Math.round(). Are you puzzled by why I use the floor function instead of the round function? I did use the round function at first, but noticed that 0 and 10 rarely occurred when using round. Here's why. Math.random() generates a random number between 0 and 0.9999.... If we multiply that number by 10, so that we get numbers greater than 1, we will get some numbers in the range of 0 to 0.49, some more numbers in the range of 0.50 to 1.49, 1.5 to 2.49…8.5 to 9.49, and 9.5 to 9.999… The only random numbers that will round to 0 are those in the range of 0 to 0.49, and the only ones that will round to 10 are those from 9.5 to 9.99. In other words, the range of numbers that will round to 0 or 10 is only half the size of the range of numbers that will round to 1 through 9. That explains why the two extremes don't appear as frequently as all of the numbers in between them. Using the floor function solves that problem, but raised another issue, which I resolved by multiplying by 11 instead of 10. I will leave it up to you to figure that one out.

We can use another one of the Math object's methods to get rid of the numbers to the right of the decimal: Math.floor(), like this:

var randomNumber = Math.floor(Math.random() * 11);

Math.floor() rounds a number down to the nearest whole number. The preceding code also demonstrates how you can nest one Math method inside of another. In this case, Javascript first generates a random number between 0 and 1, then multiplies it by 11, then submits that value to the Math.floor() function. Note that when you use this method, it is possible to generate the same random number more than once in a row.

Now you know how to generate random whole numbers within a specific range. How can this help you select a random word from a list of words? You need to construct a list of words that are indexed by whole numbers. By indexed, I mean a whole number is assigned to each word, and you can retrieve that word by the number assigned to it. The number assigned to the word is called its index. Javascript and most other programming languages have a data structure that lets you accomplish this easily: an array. An array is a variable that can contain multiple values, like this:

var weekDays = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

If we wanted to retrieve Sunday from the list and assign it to a variable named dayOfTheWeek, we could write:

var dayOfTheWeek = weekDays[0];

Javascript arrays start numbering with 0; therefore weekDays[1] equals Monday, and weekDays[6] equals Saturday. Note that we when create the array, we enclose its values in square brackets and separate each one by a comma. If the values are strings of text, we enclose each one within either single or double quotes. The comma separator must go outside the quote marks.

An array can also contain numbers:

var powersOfTwo = [2,4,8,16,32,64,128,256,512,1024];

An array can also contain variables. In the following example, I create 14 variables (p1 through p14). Each of these variables represents the HTML (HyperText Markup Language) code for inserting a picture into a web page. Then I create an array named pix, and assign those variables to the array. Then I create a custom function called RandomPictureGenerator. That function consists of two lines of code. The first line generates a random whole number between 0 and 13, using code that you learned above. The second line—the one that begins with "document.getElementById..."—inserts a random picture from the pix array into an HTML division named picture. Think of an HTML division as a box-like object. One of the properties of a division is its innerHTML, which is just the HTML code that appears inside of that division. By replacing the picture division's innerHTML with one of the variables from the pix array, I can make a random picture appear in the picture division. You can see the code in action by clicking the Display Picture button. You may need to scroll down to see the entire picture.

var p1 = "<img src='hourofcode.jpg'>";
var p2 = "<img src='state_dar_winner.jpg'>";
var p3 = "<img src='pottery.jpg'>";
var p4 = "<img src='ses_heart.jpg'>";
var p5 = "<img src='ces_aerial.jpg'>";
var p6 = "<img src='gingerbread.jpg'>";
var p7 = "<img src='matt.jpg'>";
var p8 = "<img src='mes_arbor_day_2015.jpg'>";
var p9 = "<img src='culinary-comp.jpg'>";
var p10 = "<img src='hourofcode2.jpg'>";
var p11 = "<img src='3dprinting.jpg'>";
var p12 = "<img src='inverter.jpg'>";
var p13 = "<img src='state_forensics_mshs.jpg'>";
var p14 = "<img src='summer_patterson.jpg'>";

var pix = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14];

function RandomPictureGenerator() {
    var randomNumber = Math.round(Math.random() * 13);
    document.getElementById("picture").innerHTML = pix[randomNumber];

The actual code that displays the picture is slightly different from the above code. I modified it so that the random number is also displayed. Make sure that you understand which random number corresponds to each picture. If you want to see the actual code underlying this page, just right-click the page and select "View Page Source." This will also let you see how I created the buttons on this page.

A random picture that has appeared on will appear here when you click the Display Picture button.