unique random number generator problem
i am trying to make random number generator. But the problem is, that it begins with 0 but i would to begin with 1
var Found=false
var Current = new Array()
var MaxValue=4
var NumUnique=3
开发者_StackOverflow中文版var Count=0
var Current = new Array(NumUnique)
GetUnique()
alert("The unique numbers are: " + Current[0] + ", " + Current[1] + ", and " + Current[2])
function GetUnique()
{
for (i=0;Count<NumUnique;Count++)
{
Found=false
var rndValue = get_random()
var j=0
for (j=0;j<Current.length;j++)
{
if (Current[j] == rndValue)
{
Found=true
break
}
}
if (Found)
{
Count--
} else {
Current[Count]=rndValue
}
}
}
function get_random()
{
var ranNum= Math.round(Math.random()*MaxValue);
return ranNum;
}
thanks, regards
You have a value from 0-maxvalue, and you want 1 to maxvalue? I'd suggest this
var ranNum= Math.round(Math.random()*(MaxValue-1))+1;
@Nanne's answer solves the starting with 0 element of this question but just reading this code i'd suggest you change your unique random number generator as well (although i realise this isn't the question you're asking).
Your algorithm is ok for a max-value of 4 with only 3 unique entries but if you want to start creating thousands of unique entries your algorithm is going to run really slowly the higher the number of unique numbers you want get (it's O(n^2)).
So, say, if you wanted 10000 unique numbers on the 9999th number you would scan the entire array potentially hundreds of times until you came up with a number you hadn't seen yet.
A better way to do this depends on what you want. If you want a random sequence of unique numbers in a range then it would be better to start with an ordered array of increasing values and then simply shuffle that array for a while randomly swapping values. Say for n unique numbers make n random swaps this is O(n).
If you need random numbers in a very wide range then you need to store your generated numbers in a dictionary so you can quickly look up which numbers you've already generated. I think this would also be O(n).
精彩评论