What is the simplest way to get 50 random unique elements from an array of 1000 elements ?
text = new Array();
for(i=0;i<1000;i++){ text[i]=i; } //array populated
// now I need to get 50 random unique elements from this array.
What is the simplest way to get 50 random unique elements from an array of 1000 elements ?
text = new Array();
for(i=0;i<1000;i++){ text[i]=i; } //array populated
// now I need to get 50 random unique elements from this array.
This assumes you mean random indexes and not indexes with unique values.
One way is to copy the array and prune off the ones you use:
Another way is to keep track of the indexes you use and keep looking until you find one you did not use. I find the while loop to be scary, and personally would not use this solution if random indexes needed approaches close to the array length.
Math.random() * 1000;
Generate 50 random numbers and use them as the position in the array.
Look into the Fisher-Yates algorithm, I think this will work for you.
You'll have 50 random unique numbers in the array arr, which you could use as index
EDIT:
As @ajax333221 mentioned, the previous code doesn't do to get unique elements from the array, in case it contains duplicates. So this is the fix:
Being 'text' the array populated with 1000 values
Good algorithms explained in this topic (in C but you can easily to do same in JS)
The obvious (to me) way is to shuffle the array, then take the first fifty elements. This question has a good way to shuffle an array, and you can then
slice
the first fifty elements. This guarantees the elements will be unique.So, using the function there: