算法生成1000不同的整数的范围为[0,8000] [英] Algorithm to generate 1000 distinct integers in the range [0,8000]?
问题描述
可能重复:
<一href="http://stackoverflow.com/questions/158716/how-do-you-efficiently-generate-a-list-of-k-non-repeating-integers-between-0-and">How你高效地生成介于0和上限ñ k条非重复的整数列表
什么是一些其他方法来生成1000不同的随机整数的范围为[0,8000],而不是为以下内容:
- 天真的方法:产生一个数字,并检查它是否已经到数组中。为O(n ^ 2)
- 线性洗牌:生成序列0到8000,洗牌,取前1000 O(N)
您可以使用部分的费雪耶茨洗牌实现使用互换。一个该算法的不错的功能是,如果你在 K
互换停止,第一个 K
数字是随机的大小样品 K
从配套。
Possible Duplicate:
How do you efficiently generate a list of K non-repeating integers between 0 and an upper bound N
What are some alternative methods to generate 1000 distinct random integers in the range [0,8000] as opposed to the following:
- naive method: generating a number and checking if it's already in the array. O(n^2)
- linear shuffle: generate sequence 0 to 8000, shuffle, take the first 1000. O(n)
You can use a partial Fisher-Yates shuffle implemented using swaps. One of the nice features of this algorithm is that if you stop after k
swaps, the first k
numbers are a random sample of size k
from the complete set.
这篇关于算法生成1000不同的整数的范围为[0,8000]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!