I need to randomize set of values in JS, and I call function randomize for example three times. How can I remember and block random generator from giving me results that it gave me previous times? I can only give one value once.
var value = Math.floor(Math.random() * 11);
One of the wonderful randoms are provided by allocating sequential array of int:
And after it you shift numbers there in order Math.floor(Math.random() * myArr.length);
benefit of such approach - you get non-repeatable sequence of any length.
Judging from your comments, it sounds like you have a small range of values (i.e. from 1-10) which you want to randomly select your values from. In that case your best bet is to store your values in an array and randomly splice them out. I prefer to perform these kinds of operations using some sort of generator.
To use the generator creator, provide it with your short list of unique values, and store the result. The result is a generator you can use to generate N number of random numbers from your list of unique values. (Where N is the length of the array you seeded your random generator with).
You can then use the generator by calling the generator that that function returns over and over.
If you do not have a pre-defined set of numbers you wish to use, I'd recommend Török Gábor's solution above.
Cheers!
Instead of using Random(), you can use time ticks which will give you a random value everytime you use them -
Or, you can extend the default JS
Array
, and add thecontains
method to it. Every random value you generate will be added to the array, but before adding, thecontains
method will check whether it already exists in the array or not.Use a hash.
Then you can dump all of those into an array if you want - that's O(n).
Something like this (tested):
What is your larger goal? If you're trying to select items from a finite set in a random order, then you'll want to look at using a shuffle algorithm to randomize the ordering and then remove them in the resulting shuffled order as needed.