Generating Random Numbers
By Stephen Bucaro
The Math.random method returns a floating-point value between 0 and 1.
To generate a random integer between zero and n, use the formula below:
var num = Math.floor(Math.random() * n);
To generate a random integer between m and n, use the formula below:
var num = Math.floor(Math.random() * (n - 1)) + m;
For example, if you wanted to design a card game you would need random
integers between 1 and 52. These random numbers could be generated with the line
shown below.
var card = Math.floor(Math.random() * 51) + 1;
The example below places the names of the cards in an array and then
generates a random integer between 1 and 52, which it uses as an index into the
array to display the name of a card.
var arCard = new Array(
"A club","2 club","3 club","4 club","5 club","6 club","7 club","8 club","9 club","10 club","J club","Q club","K club",
"A diam","2 diam","3 diam","4 diam","5 diam","6 diam","7 diam","8 diam","9 diam","10 diam","J diam","Q diam","K diam",
"A heart","2 heart","3 heart","4 heart","5 heart","6 heart","7 heart","8 heart","9 heart","10 heart","J heart","Q heart","K heart",
"A spade","2 spade","3 spade","4 spade","5 spade","6 spade","7 spade","8 spade","9 spade","10 spade","J spade","Q spade","K spade");
var card = Math.floor(Math.random() * 52) + 1;
document.write(arCard[card]);
You might use a for loop, as shown below, to "draw" a random five card
poker hand. Each time the webpage is loaded, a random poker hand will be displayed.
var card;
for(var i = 1; i < 6; i++)
{
card = Math.floor(Math.random() * 52) + 1;
document.write(arCard[card] + " - ");
}
The example below places the file names for six die images into an array. Each
time the webpage is loaded, a random pair of die images will be displayed.
var arDie = new Array("1.gif","2.gif","3.gif","4.gif",
"5.gif","6.gif");
var roll;
for(var i = 1; i < 3; i++)
{
roll = Math.floor(Math.random() * 5) + 1;
document.write("<img src='" + arDie[roll] + "'>");
}
Random numbers have many uses, from the creation of passwords, generation of abstract
art, generation of artificial worlds, to games such as dice and cards. The Java Script
Math object's random method returns a floating-point value between 0 and 1. To generate
a random integer between zero and n, use the formula provided here.
More Java Script Code: • The for Loop • Convert a String to a Number • Cookie Power Made Easy • Rounding a Number with JavaScript • The while Loop • Convert a Number to a String • Format a Number as Currency • Define Lines in a String • The Browsers History Object • Using the Java Script eval() Function
|