. 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 type="text/javascript'> function random_3(){ var myrandom=Math.round(Math.random()*2) var link1="http://www.codingforums.com" var link2="http://www.cssdrive.com" var link3="http://www.dynamicdrive.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 10 predetermined links:
<script type="text/javascript"> function randomlinks(){ var myrandom=Math.round(Math.random()*9) var links=new Array() links[0]="http://www.javascriptkit.com" links[1]="http://www.dynamicdrive.com" links[2]="http://www.cssdrive.com" links[3]="http://www.codingforums.com" links[4]="http://www.news.com" links[5]="http://www.gamespot.com" links[6]="http://www.msnbc.com" links[7]="http://www.cnn.com" links[8]="http://news.bbc.co.uk" links[9]="http://www.news.com.au" window.location=links[myrandom] } </script> <form> <input type="button" value="random link!" onClick="randomlinks()"> </form>
As you can see, to create a random link out of 10, we multiplied Math.random() by 9 to first generate a random number that falls between 0 and 9. Then by using the round() method, we molded this number into an integer. Finally, a new technique here- I use arrays to store the links so I can easily reference here. This is a lot more desirable when you have a lot of links to define and need to pick one out.
- Tutorial introduction
- Understanding the two methods of the Math object required to create a random engine
- Creating a random link out of a specified group of links
- Creating a random link out of all of the links in a document
- Looking at other uses of a random engine- simulating a dice throw + Math object summary