这些算法是在性能和​​更好的顺序用于生成1..N范围n独特的随机数? [英] Which of these algorithm is better in performance and order for generating N unique random number in 1..n range?

查看:166
本文介绍了这些算法是在性能和​​更好的顺序用于生成1..N范围n独特的随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

径的阵列n个元素:{1,2,3,... n}的。洗牌使用任何随机洗牌阵列的标准算法的数组。修改后的数组的第N个元素就是你所期待的。

Take an array of n elements: { 1, 2, 3, .... n }. Shuffle the array using any of the standard algorithms of randomly shuffling arrays. The first N elements of the modified array is what you are looking for.

只需使用 Random.Next()在一个循环,并检查是否已存在或者未在词典 ,直到我们有N个。

Simply use Random.Next() in a loop and check if it already exists or not in an Dictionary, until we have N numbers.

请注意,N'LT;< N(N是小于n非常小)

Notice that N << n ( N is very smaller than n)

推荐答案

部分费雪耶茨,一些调整*:

Partial Fisher-Yates, with some tweaks*:

<一个href="http://stackoverflow.com/questions/2576023/algorithm-to-generate-1000-distinct-integers-in-the-range-0-8000/2576178#2576178">Algorithm产生1000不同的整数的范围为[0,8000]

&安培;

<一个href="http://stackoverflow.com/questions/2394246/algorithm-to-select-a-single-random-combination-of-values/2394308#2394308">Algorithm选择一个单一的,随意组合价值?

<子> *这里主要的外卖是,内存使用量减少,所以现在是成正比的项目数的选择的最多的项目数量不限的选择。这可以提供巨大的节能,如果 N'LT;&LT; ñ(正如你所提到的)。 (使用空间的上限是为O(n / 2),不管作如何收盘为n。)

* The main takeaway here is that memory usage is reduced, so it is now proportional to the number of items selected at most, not the number of items selectable. This can provide major savings if N << n (as you have mentioned). (Space usage is capped at O(n/2), no matter how close N is to n.)

<子>运行时间为O(N)。

<子>除此之外,它是一个相当常用的部分费雪耶茨,又名克努特洗牌。

这篇关于这些算法是在性能和​​更好的顺序用于生成1..N范围n独特的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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