admin管理员组

文章数量:1318992

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.
Share Improve this question edited May 21, 2012 at 16:30 ajax333221 11.8k16 gold badges62 silver badges95 bronze badges asked May 21, 2012 at 15:20 xRobotxRobot 26.6k72 gold badges192 silver badges316 bronze badges 1
  • 2 What do you mean by unique elements? You mean unique indexes or unique values in the indexes? – epascarello Commented May 21, 2012 at 15:54
Add a ment  | 

7 Answers 7

Reset to default 4

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:

fisherYates(text);
text = text.slice(0, 50);

Good algorithms explained in this topic (in C but you can easily to do same in JS)

Look into the Fisher-Yates algorithm, I think this will work for you.

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:

function getRandomIndexes( arr, cnt){
    var randomArr = [],
        arrCopy = arr.slice(),
        i, 
        randomNum ;
    for (i=0;i<arrCopy.length;i++) {
        randomNum = Math.floor( arrCopy.length * Math.random());
        randomArr = randomArr.concat(  arrCopy.splice(randomNum ,1) );
    }    
    return randomArr;
}

var myNums = [], i, randSet;
for (i=0;i<10;i++){
    myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);

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.

function getRandomIndexes( arr, cnt){
    var randomArr = [],
        usedNums = {},
        x;
    while (randomArr.length<cnt) {
        while (usedNums[x]===true || x===undefined) {
            x = Math.floor( Math.random() * arr.length);
        }
        usedNums[x] = true;
        randomArr.push( arr[x] );
    }
    return randomArr;
}

var myNums = [], i, randSet;
for (i=0;i<10;i++){
    myNums.push(i);
}
randSet = getRandomIndexes(myNums, 5);

In case you meant unique values:

Demo

var old_arr = [0,1,2,3,4,5,6,7,8,9], new_array = [];

for (var i = 0; i < 5; i++) {
    var rand_elem = old_arr[Math.floor(Math.random() * old_arr.length)];

    if (arrIndex(old_arr[rand_elem], new_array) == -1) {
        new_array.push(rand_elem);
    } else {
        i--;
    }
}

function arrIndex(to_find, arr) {//own function for IE support
    if (Array.prototype.indexOf) {
        return arr.indexOf(to_find);
    }
    for (var i = 0, len = arr.length; i < len; i++) {
        if (i in arr && arr[i] === to_find) {
            return i;
        }
    }
    return -1;
}

In case you meant unique indexs:

  • Generate random indexes and store the indexes in an array and make checks to prevent duplicates
  • Start removing the elements of the array after you get them, (you might have problems if you cache the length, so don't)
var arr = [];
while(arr.length < 51){
    var ind = Math.floor(Math.random()*1000);
    if(!(ind in arr))
        arr.push(ind)
}

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:

var result_arr = [];
while(result_arr.length < 51){
    var ind = Math.floor(Math.random()*1000);
    if(text[ind] && !(text[ind] in result_arr))
        result_arr.push(text[ind]);
}

Being 'text' the array populated with 1000 values

Math.random() * 1000;

Generate 50 random numbers and use them as the position in the array.

本文标签: javascript50 random unique elements from an array of 1000 elemensStack Overflow