My Experiments with Random number in JavaScript

Recently somebody asked me about how to generate a random number in JavaScript. While explaining him the basics of it, refreshed my experiments with the random number generation in JavaScript, which triggered this blog post.

In recent times most of the web applications make use of JavaScript for client side logic. Due to availability of several powerful third-party JavaScript libraries, developer’s life has become easy, writing the JavaScript code. However for small use of JavaScript it may not be possible/advisable to load these 3rd party libraries in the application. In such cases basic functions provided by JavaScript might be handy.

For example generating random numbers using the basic JavaScript is pretty trivial. With the simple tweak one can have several variations to generate the random. Sharing some of my experiments done with generating random numbers using JavaScript.

Basic Function

Let’s look at the basic form of the random function in JavaScript.

Math.random()

Above function generates the random numbers between 0 and 1. So if you try printing the results of this function on the browser, the generated numbers might look like this.

0.6001346987898531
0.37660487408682053

Expanding the range

What if I want to generate the random numbers bigger than 1? The trick is to use multiplier. Since basic function generates random fractions between 0 and 1, the multiplier number increases the upper limit of the range to the multiplier.

Math.random() * 11

Using multiplier 11, one can generate random numbers between 0 and 10.

9.378415845093869
3.6694326353729254

You may see the results something like this. They are still with the fractions and not the whole numbers.

Truncating the fractions

Function Math.floor() is there for rescue to remove the fractions from the generated numbers. It returns the whole part of the number by truncating the factional part of it.

Math.floor(Math.random() * 11)

One can even write a quick utility function as below.

<script type="text/javascript">
function generateRandomInteger(maxRange) {
	return Math.floor(Math.random() * maxRange);
}
</script>

The results returned by the above function will be whole numbers. However there is a catch. It does not guarantee the unique random number in succession. So if there is a need to generate a unique random numbers in a loop this might not work. It is possible that the number generated repeats when called in succession.

And the reason is simple. The number generated by Math.Random() function is in fraction. And small fractional difference between 2 numbers is also considered as non-repeated random number. However due to use of multiplier and the truncation, the whole part of the number is the same and due to use of Math.floor() function one gets the same number multiple times.

For example numbers 9.378415845093869 and 9.478415245093169 are unique random numbers, but after using Math.floor() function both becomes 9.

Generate Unique Random

To resolve this duplicate random number issue, I have used a while loop to check the duplication and regenerate the number before return. Here is the modified generateRandomInteger() function.

<script type="text/javascript">
var lastNum = 0;
function generateRandomInteger(maxRange) {
	while(true) {
		var randomNumber = Math.floor(Math.random() * maxRange);
		if(lastNum != randomNumber) {
			lastNum = randomNumber;
			break;
		}
	}
	return lastNum;
}
</script>

In the above example the while loop which iterate to find out the unique random number as compare to the last generated number. As you see there are drawbacks of this approach and couple of them listed below.

  1. There is a need of tracking the last generated number to compare with the newly generated random number. In the above example the variable is lastNum. Assume this function is called from different locations, the last number generated for one caller may not match with the other caller. Since lastNum need to be global variable, the same will be used for multiple callers. And there are chances of getting the non-unique number in succession in case of multiple callers. Also this functions assume the script is loaded once and the variable lastNum does not reset to 0 for every call of function.
  2. The biggest drawback could be the while loop. The condition of the loop is always true and virtually it is an infinite loop. For small values of maxRange it might iterate several times by degrading the overall performance of the application. Especially when some operation is dependent on the return of this function. When calling this function by passing 1 as maxRange will take the while loop into infinite iterations.

To overcome the first drawback mentioned, the crude way could be that the caller also passes the last generated value to the function.

For the later case, the small values can be handled by adding the break after certain predefined iteration. However this does not guarantee the unique random numbers. The other workaround would be to specify some minimum limit for this input parameter passed. For example it should be greater than 8.

What if there is a need to generate the random number between the range. Either we can use the above function to achieve this by controlling the input parameter. Or write a new function which takes the min and max of the range to generate the number. Next section details the experiment of the same.

Generate Unique Random between Range

Logically the current function generateRandomInteger() above also returns the random number between the range. Just that the min or lower integer is implicit and always zero. That derives a new function which takes 2 parameters for min and max integer of the range. The obvious implementation of the function may look like this.

<script type="text/javascript">
var lastNum = 0;
function generateRandomIntegerForRange(minRange, maxRange) {
	while(true) {
		var randomNumber = Math.floor(Math.random() * maxRange);
		if((lastNum != randomNumber) && (randomNumber > minRange)) {
			lastNum = randomNumber;
			break;
		}
	}
	return lastNum;
}
</script>

The logic in the modified function primarily generates the random number between 0 and the maxRange. However there is extra check to confirm whether the unique random is greater than the minRange before returning the unique number.

The function logic can be further simplified while keeping the same check in the IF loop as earlier function generateRandomInteger(). Where the random will be generated between 0 and (maxRange - minRange) and then add minRange to it. So the function will look like this.

<script type="text/javascript">
var lastNum = 0;
function generateRandomIntegerForRange(minRange, maxRange) {
	while(true) {
		var randomNumber = Math.floor(Math.random() * (maxRange - minRange)) + minRange;
		if(lastNum != randomNumber) {
			lastNum = randomNumber;
			break;
		}
	}
	return lastNum;
}
</script>

Both the above approached have the same drawbacks of the earlier functions. In this case the difference between maxRange and minRange should not be too small.

Note that in the example code I have not added the validation such as whether the parameter passed to function is indeed a number, maxRange is greater than minRange and so on. Similarly the drawbacks listed above can be very well handled with few more lines of code.

These were some of my experiments with the JavaScript random number generation. Feel free to extend it with your comments.

Advertisements

Posted on February 22, 2012, in JavaScript, tech, web development and tagged , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: