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.
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.
You may see the results something like this. They are still with the fractions and not the whole numbers.
Truncating the fractions
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.
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.478415245093169 are unique random numbers, but after using
Math.floor() function both becomes
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
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.
- 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
lastNumneed 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
lastNumdoes not reset to 0 for every call of function.
- The biggest drawback could be the
whileloop. The condition of the loop is always true and virtually it is an infinite loop. For small values of
maxRangeit 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
maxRangewill 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.
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
(maxRange - minRange) and then add
minRange to it. So the function will look like this.
Both the above approached have the same drawbacks of the earlier functions. In this case the difference between
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.