javascript random string
The Original Web-Wise-Wizard
Web Authors, Web Developers and Webmasters Internet Toolbox
javascript random seed
javascript random color
javascript random colour
random image generator
Best viewed at 1024 x 768 using a colour depth greater than 256

JavaScript Random Number Arrays

This page has been tested and conforms to WCAG 2.0 Accessibility Guidelines

Generate Random Numbers ...

Generating random numbers is often considered a 'black art' yet in reality it is really very simple. This step-by-step tutorial starts with the basic principles of random number generation in JavaScript. It then continues where other Math.random tutorials finish by showing you how to fill a JavaScript array with unique, randomly generated numbers. Full detailed demonstrations provided. Ideal for both experienced scripters and newcomers to JavaScript/JScript scripting.

 

JavaScript Math.Random() ...

JavaScript has a pseudo random number generator function which is a static method of the JavaScript 'Math' object and is used in the form 'x = Math.random()'. Computers are not able to generate true random numbers so JavaScript seeds it's random number generator using the time (in miliseconds) which is provided by the JavaScript 'Date' object. The random number generator always returns a value between 0 and 1.

At first glance this doesn't appear to be too exciting until you realise that each number returned is a decimal fraction of one (e.g. '0.9985605959949931'). We have provided the demo below to illustrate the operation of the Math.random() function. Just try clicking the button to see the pseudo value generated. Then try is several times more to study the results and understand the Math.random() operation.

 
 

Useful Random Numbers ...

Decimal numbers in the form returned by Math.random() do not appear to be very useful for any purpose that I can think of so we must now set about making them useful for realtime purposes.

We must first decide upon the highest random number we want to generate and for the purposes of this example we shall set the figure to 20. We have provided this further demo which generates a pseudo random number in the range 0...20. Try is several times to test that the numbers range between 0 and 20.

 

We can then make our script even more useful by deciding on the lowest random number we want to generate and for the purposes of this example we shall set the figure to 5. We have provided another demo which generates a pseudo random number in the range 5...20. Try is several times to test that the numbers range between 5 and 20.

 

We would normally use this script in it's own 'universal' function and an example JavaScript script is provided which you can copy 'as is' if you wish to do so. It is worth studying the script in relation to the examples above to understand it's operation.

 

a basic random number script...

// RETURNS PSEUDO-RANDOM NUMBER IN RANGE min...max
function random_number(min,max) {

    return (Math.round((max-min) * Math.random() + min));
}
 
+++ Quick Calculation +++
Calculate how many programmers it takes to change a light bulb?  None! It's a hardware problem.
 

Non-Unique Random Array ...

Now that we know how to generate a single random number within a given range we can move on to creating and filling a JavaScript array with random numbers.

If you don't require the numbers in the array to be unique (i.e. you don't mind duplicated numbers) then this is a straight forward task and the script displayed below would achieve this. First we use the script to provide a demonstration of filling an array of 16 elements (0...15) with non-unique pseudo random numbers in the range 5...20. If you check the generated numbers you should be able to spot duplications and again, you can try it several times to check the operation.

 

the non-unique array (check for duplications)...

  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
 

the non-unique array script...

// CREATE AND FILL NUMBER ARRAY WITH NON-UNIQUE RANDOM NUMBERS
var myNumArray = create_non_unique_random_array(16,5,20);

function create_non_unique_random_array(num_elements,min,max) {

    var nums = new Array;

    for (var element=0; element<num_elements; element++) {
        nums[element] = random_number(min,max);
    }

    return (nums);
}
 

Unique Random Array ...

Now we move on to the slightly more difficult task of creating a JavaScript number array containing unique random numbers (i.e.no duplications). This is basically the same as the previous script except that there is an extra function which tests to see if the array already contains the next random number.

The script is displayed below, following the demonstration which uses the script. If you check the numbers generated in the demonstration you will see that the full range of numbers (5...20) are displayed in each time you click the demo button. There are no duplications and only the random order changes each time. Yet again, you can try it several times to check the operation.

 

the unique array (this time, you won't find duplications)...

  • 0
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
 

the unique array script...

// CREATE AND FILL NUMBER ARRAY WITH UNIQUE RANDOM NUMBERS
var myNumArray = create_unique_random_array(16,5,20);

function create_unique_random_array(num_elements,min,max) {

    var temp, nums = new Array;

    for (var element=0; element<num_elements; element++) {

        //IMPORTANT: DON'T FORGET THE SEMI-COLON AT THE END
        while((temp=number_found(random_number(min,max),nums))==-1);
        nums[element] = temp;
    }

    return (nums);
}

function number_found (random_number,number_array) {

    for (var element=0; element<number_array.length; element++) {

        if (random_number==number_array[element]) {
            return (-1);
	}
   }

    return (random_number);
}
 

Why Random Arrays? ...

If you have read the tutorial and are wondering what you would use random arrays for, there are literally hundreds of uses once you learn how to create them and you start to realise their potential. Applications could include games like dice, dynamic HTML demos, random image scripts, random link generators, quizzes, etc., the list is endless.

Perhaps the most notable example of their usage in in Web-Wise-Wizard is on our Home Page Introduction page. Here we create new random index arrays for the features column and the banners column, every time the page is loaded. This enables us to use the same information each time the user views the page, but the items are presented in a totally different random order. The same random arrays also provide the foundation for the novel 'spin' feature in these columns.

 

Link Directly To This Page ...

help support free information on the Internet ...

Many users prefer to link directly to individual content pages on Web-Wise-Wizard. If you would like to do this then we have provided the following HTML/CSS link script which you can copy and paste directly into your HTML editor. Alternatively, you might like to use our New Dynamic Link Generator to create a link that more fully meets your own particular requirements.

the link displayed ...

Web-Wise-Wizard - JavaScript Random Arrays Learn how to generate JavaScript random numbers. Full demonstrations of how to use the random method of the JavaScript Math object and how to create a unique random array in your JavaScript scripts.

select/copy the link Markup ...

Featured Tutorial
Want More Traffic? Increase your Link Popularity and your PageRank by learning how to use Web Directories
Link To Us Scripts
New Dynamic Link Generator
 
If you find this page interesting or useful then others are likely to view it in exactly the same way. Providing a link to the page will be considered by the search engines as casting a vote for the page. In turn, this will help to improve the search engine ranking of the page resulting in more people being able to see the page. Your link really does count so please don't delay.
 
Post your link NOW!
 
 
JavaScript Random Number Resources
 
 
javascript random string javascripy javascript random text
 
 
 
javascript random array
random quote generator
random image generator
javascript image rotator
random image script javascript
Copyright © 1998,2008, Gilbert Hadley, Liverpool, England
 
miscellaneous random image