50 random unique elements from an array of 1000 el

2020-02-14 02:53发布

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.

7条回答
Anthone
2楼-- · 2020-02-14 03:13

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);
查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-14 03:14

Math.random() * 1000;

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

查看更多
虎瘦雄心在
4楼-- · 2020-02-14 03:22

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

查看更多
甜甜的少女心
5楼-- · 2020-02-14 03:24
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

查看更多
乱世女痞
6楼-- · 2020-02-14 03:27

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

查看更多
兄弟一词,经得起流年.
7楼-- · 2020-02-14 03:33

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);
查看更多
登录 后发表回答