Easy Java Script Code to Fill Array With Random Numbers
By Stephen Bucaro
In programing we occasionally find the need to fill an array with random numbers.
This might be useful in game code, or in my particular case, selecting random questions
for a certification practice exam. Search the internet and you'll find all kinds of
convoluted code for this purpose. The code I present here might not be the fewest lines
possible, but it is the easiest to understand. The code to fill an array with with
random numbers is shown below.
var qarray = new Array(30);
var j = 0;
var min = 171;
var max = 218;
while(j < qarray.length)
var randnum = Math.floor(Math.random()*(max-min+1)+min);
var found = false;
for(var i = 0; i < qarray.length; i++)
if(qarray[i] == randnum)
found = true;
qarray[j] = randnum;
document.write(qarray[j] + "<br />");
Here's a brief explanation of how the code works:
1. In the first line an array with 30 members named qarry is declared. To change the
size of the array, simply edit the number 30. The variable j is used as an index to
scan through the array.
2. The variables min and max set the lowest and highest random numbers that will be
created. Change these to set the range of random numbers generated for your application.
3. The while loop executes the code within it's body until the entire array is full
of random numbers.
4. The first line within the while loop uses the Java Script Math object's random function
to create a random floating-point number between 0 and 1. The remainder of the line in
parenthesis sizes the random floating-point number to the proper range. The Math
object's floor function removes the decimal part of the number, returning an integer.
5. The variable found is a boolean that is initialized to false. The for loop following
that runs through the array comparing the newly generated random number to each element
in the array. If it finds that number is already in the array, it sets found to true and
breaks out of the loop going back to generate another random number.
6. If the newly generated random is not found in the array, the if statement sets the
next available element in the array to that number, writes that number to the document,
increments the index j, and returns to the while loop's test statement.
7. When the while loop's test statement turns false, indicating the array is full, the
loop exits and and the script finishes.
There you have it, simple code to to fill an array of any size you choose with a range
you choose of random numbers.
More Java Script Code:
• Creating Java Script Dynamic or anonymous Functions at Runtime
• Calculators for Your Web Site : Loan Payment Calculator
• Java Script Comparison Operators
• Password Protection Using the Frames Method
• Allowing Multiple Selections from Drop-down Select List
• Easy Expanding Banner Code
• Calendars for Your Website
• Easy Fading Text Banner Code