算法生成1000不同的整数的范围为[0,8000] [英] Algorithm to generate 1000 distinct integers in the range [0,8000]?

查看:156
本文介绍了算法生成1000不同的整数的范围为[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],而不是为以下内容:

  1. 天真的方法:产生一个数字,并检查它是否已经到数组中。为O(n ^ 2)
  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:

  1. naive method: generating a number and checking if it's already in the array. O(n^2)
  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆