50 random unique elements from an array of 1000 elements?

What is the easiest 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.
+3
source share
8 answers

The obvious (for 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 slicefirst fifty elements. This ensures that the items are unique.

So using the function there:

fisherYates(text);
text = text.slice(0, 50);
+3
source

The good algorithms described in this section (in C, but you can easily do the same in JS)

+1
source

, Math.random(), . , 1000. 50 .

0
0

:

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;
}

:

  • ( , , )
0
var arr = [];
while(arr.length < 51){
    var ind = Math.floor(Math.random()*1000);
    if(!(ind in arr))
        arr.push(ind)
}

arr 50 ,

EDIT:

@ajax333221, , , . , :

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]);
}

"", , 1000

0

, , .

- , :

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);

, , , , . , while , , , .

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);
0
source

Math.random () * 1000;

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

-2
source

All Articles