来自1000个elemens数组的50个随机独特元素? [英] 50 random unique elements from an array of 1000 elemens?
本文介绍了来自1000个elemens数组的50个随机独特元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
从1000个元素的数组中获取50个随机唯一元素的最简单方法是什么?
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.
推荐答案
显而易见的(对我而言)方式是洗牌数组,然后采取前五十个元素。 这个问题有一个很好的方法来重新排列数组,然后你可以< a href =https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/slice\"rel =nofollow noreferrer> slice
前五十个元素。这保证了元素的独特性。
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.
因此,使用函数:
fisherYates(text);
text = text.slice(0, 50);
这篇关于来自1000个elemens数组的50个随机独特元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文