experts
- I wish to generate unique random numbers between two numbers (from text box of web page).
- I am using array to store numbers. when user click button it gives first random number, store it in array, and when user clicks button again, it generate random number, compares it with array numbers, and if different, stores it and displays it.
- If maximum possible different numbers are show it, clears array and informs user.
- I have written code, but it gives error : stack overflow, or sometimes I get duplicate results shown.
Can anyone shed a light on code:
var allnums = new Array();
var num1= new Number;
var num2= new Number;
function funClick()
{
var num1 = Number(document.getElementById('lnum').value);
var num2 = Number(document.getElementById('hnum').value);
if (allnums.length==num2)
{
alert("Maximum non-duplicate numbers served. Now resetting the counter.");
allnums = [];
return;
}
if (num1<num2)
{
x = Math.floor(Math.random() * (num2 - num1 + 1)) + num1;
funShow(x);
}
else
{
alert("You entered wrong number criteria!");
}
}
function funShow(x)
{
var bolFound = false;
for (var i=0;i<allnums.length;i++)
{
if((allnums[i])==x)
{
funClick();
}
}
if (bolFound == false)
{
document.getElementById('rgen').innerText = x;
allnums.push(x);
}
}
I fail to see how that code is generating a stack overflow (even though
funShowhas a call tofunClickandfunClickhas a call tofunShow,funShow‘s call tofunClickshould never happen because of a logic error — fix the error and you’ll get a stack overflow, though), but it has several issues. See the comments:There are two ways to approach this. Here’s one that’s basically what you were trying to do, but without recursion:
Live Example | Source
The problem with that is that it can take a long time to fill the last few slots, since we have to hit them randomly.
The other way is to produce the array with the numbers in order, then mess it up. It can be dramatically more efficient for large ranges. Something like this:
Live Example | Source
But, just doing the
nums.sort(...)randomly once may well not be as successful at producing random results; see this article for more. (Thanks to eBusiness for that link and for his input on the below.)So you may want to go further and throw in further random operations. Here’s another example:
Live Example | Source
That does the array sort thing as a starting point, but then does a bunch of random swaps between elements as well. It still runs in constant time, but should have a better result than using the array sort alone. Naturally, you’ll want to test the distribution.