50 random unique elements from an array of 1000 elemens?

前端 未结 7 880
忘掉有多难
忘掉有多难 2020-12-21 01:22

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         


        
7条回答
  •  情深已故
    2020-12-21 02:07

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

提交回复
热议问题