
Lesson 18-Using the random method to create random scripts
The word "random" has always raised interesting debates between mathematicians and philosophers. Do events in life really occur randomly or not? I don't know about you, but among JavaScripters, we just don't care about these philosophical issues. All we care about is how to simulate this randomness to create a "random engine" that can be applied to scripts. Scripts using this random engine will behave randomly, not to be confused with erratically! Ok, in this lesson, we'll look at:
Understanding the two methods of the Math object required to create a
random engine
While it is safe for us to ditch the philosopher, it's not exactly wise to do the same with the mathematician. Mathematics play a pivital role in JavaScript when creating a random engine, in the form of the Math object. Don't worry, you don't have to be a math wiz to understand how to create a random engine. Now that we've clarified that, the Math object of JavaScript has many propeties and methods, and we will list them all at the end of this lesson. For now, however, lets simply investigate the two methods neccessary to continue on with our current discussion:
| Method | Description |
| random() | Returns a random number between 0 and 1, although the number returned is usually in between, in the form of 0.xxxxxxxxxxxxxxxxx |
| round(num) | Returns the specified number rounded to the nearest integer. |
Lets break down these methods now.
random()
The random() method of the Math object returns a random number between 0 and 1, although its important to realize that this number is usually in between, (0.xx..., with 17 decimals). The random() method ultilizes the clock in the client's computer to generate this number. Lets see it in action:
<form>
<input type="button" value="random number" onClick="alert(Math.random())">
</form>
Click on the above example multiple times; the number alerted will be different each and every time. Notice the syntaz:
Math.random()
The first letter of "Math" HAS to be capitalized if you don't want to end up banging your keyword against the desk!
We now know in general how to generate a random number in JavaScript.
round()
A random number with 17 decimal points can be quite hard to work with...here's where the round() method comes in. The round() method of the Math object rounds any given number to the nearest interger. Here are a few simple examples:
Math.round(3.4564) //returns 3
Math.round(3.6) //returns 4
Math.round(234.342) //returns 234
We now have all the tools we need to simulate randomness!
Creating a random link out of a specified group of links
One of the most common uses of a random engine is to create a random link out of a predetermined group of links. We specify in advance the urls to be put in a "black box", and have the random engine randomly draw one out to follow. Let's first create a random link out of three predetermined links:
<script>
function random_3(){
var myrandom=Math.round(Math.random()*2)
var link1="http://www.abstract.simplenet.com"
var link2="http://www.geocities.com"
var link3="http://www.abcnews.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
}
</script>
<form>
<input type="button" value="random link!"
onClick="random_3()">
</form>
The meat of this example is the following:
var myrandom=Math.round(Math.random()*2)
The above creates a random integer between 0 and 2. The number could be 0,1, or 2. Let's see more finely why this is the case.
1) Math.random() always produces a random number between 0 and 1
2) Math.random()*2 always produces a random number between 0 and 2
3)
Math.round(Math.random()*2) always
produces a random integer between 0 and 2
Understanding the above enables us to create a random integer that falls between 0 and any integer! Lets extend the current example to create a random link out of 5 predetermined links:
<script>
function random_5(){
var myrandom=Math.round(Math.random()*4)
var link1="http://www.abstract.simplenet.com"
var link2="http://www.geocities.com"
var link3="http://www.microsoft.com"
var link4="http://www.netscape.com"
var link5="http://www.infoseek.com"
if (myrandom==0)
window.location=link1
else if (myrandom==1)
window.location=link2
else if (myrandom==2)
window.location=link3
else if (myrandom==3)
window.location=link4
else if (myrandom==4)
window.location=link5
}
</script>
<form>
<input type="button" value="random link!"
onClick="random_5()">
</form>
As you can see, to create a random link out of 5, we multiplied Math.random() by 4 to first generate a random number that falls between 0 and 4. Then by using the round() method, we molded this number into an integer. If we want a random number that falls between 0 and 100, we should multiply Math.random() by 99.
Creating a random link out of all of the links in a document
Using the links object we've learned from last chapter, along with the information from this, we can create a generic random link that uses all of the links in the document as its "ammunition". Lets see how a script like this is implemented:
<script>
function random_all(){
var
myrandom=Math.round(Math.random()*(document.links.length-1))
window.location=document.links[myrandom].href
}
</script>
The above script may be short, but it is very powerful! It can be inserted into any document to instantly create a random link out of all of the links in the document. Before we go any further, lets put the above script in a document and see it in action:
The technique used to create this script is quite simple. By using the length property of the links object, we first generated a random number that falls in the range of 0 and the index number of the last link in the document:
var myrandom=Math.round(Math.random()*(document.links.length-1))
Then by using this random number as an index number to reference a random link in the document:
window.location=document.links[myrandom].href
We create a random link that draws a url out of all of the links in the document!
Looking at other uses of a random engine- simulating a dice throw
Remember, a JavaScript random engine can be used to power any script that requires the quality of randomness, although its used mainly by JavaScripters on the net to create random links.
The throw of a dice is another classic example of a random event. Lets use the knowledge obtained thus far to recreate this event. To acheive this, we will first need six images of the same size, each representing one "face" of the dice:

The idea is to use the random engine to randomly load one of the six faces of the dice each time the dice is "thrown", and display the image in place of the old. The below example illustrates this:
<html>
<head>
<script>
//preload the six images first
var face0=new Image()
face0.src="d1.gif"
var face1=new Image()
face1.src="d2.gif"
var face2=new Image()
face2.src="d3.gif"
var face3=new Image()
face3.src="d4.gif"
var face4=new Image()
face4.src="d5.gif"
var face5=new Image()
face5.src="d6.gif"
</script>
</head>
<body>
<img src="d1.gif" name="mydice">
<form>
<input type="button" value="Throw dice!"
onClick="throwdice()">
</form>
<script>
function throwdice(){
//create a random integer between 0 and 5
var randomdice=Math.round(Math.random()*5)
document.images["mydice"].src=eval("face"+randomdice+".src")
}
</script>
</body>
</html>
There really isn't anything new here; we simply used the random() method to first generate a random number between 0 and 5, attached this number to the remaining path of the "face" image, and boom- we have a dice! Note that IE 3.x and NS 2.x does not support the image property used above to change the dice image, so the above code will not work with these browsers.
before we wrap up this chapter, lets list all of the properties/methods of the Math object, as promised:
| properties | methods |
| E | abs(num) |
| LN2 | acos(num) |
| LN10 | asin(num) |
| LOG2E | atan(num) |
| LOG10E | ceil(num) |
| PI | cos(num) |
| SQRT1_2 | exp(num) |
| SQRT2 | floor(num) |
| log(num) | |
| max(num1,num2) | |
| min(num1,num2) | |
| pow(num,power) | |
| random() | |
| round(num) | |
| sin(num) | |
| sqrt(num) | |
| tan(num) |
What's next? Well, lets move on to arrays- using them, sorting them, and eventually shifting dimensions with them- by the time we come back up, you'll love and use arrays a lot more than you've ever had!