样品K随机排列,而不更换O(N) [英] Sample k random permutations without replacement in O(N)
问题描述
我需要一个号码列表的唯一随机排列而不更换,高效。我目前的做法:
I need a number of unique random permutations of a list without replacement, efficiently. My current approach:
total_permutations = math.factorial(len(population))
permutation_indices = random.sample(xrange(total_permutations), k)
k_permutations = [get_nth_permutation(population, x) for x in permutation_indices]
其中, get_nth_permutation
不正是它听起来像,有效(意为O(N))。但是,这仅适用于 len个(人口)LT = 20
,仅仅是因为21!如此mindblowingly久,的xrange(math.factorial(21))
将无法工作:
where get_nth_permutation
does exactly what it sounds like, efficiently (meaning O(N)). However, this only works for len(population) <= 20
, simply because 21! is so mindblowingly long that xrange(math.factorial(21))
won't work:
OverflowError: Python int too large to convert to C long
有没有更好的算法,以样本k独特的排列没有更换O(N)?
Is there a better algorithm to sample k unique permutations without replacement in O(N)?
推荐答案
而不是使用的xrange
只是继续产生随机数,直到你有很多,你所需要的。使用设置
确保它们都是唯一的。
Instead of using xrange
simply keep generating random numbers until you have as many as you need. Using a set
makes sure they're all unique.
permutation_indices = set()
while len(permutation_indices) < k:
permutation_indices.add(random.randrange(total_permutations))
这篇关于样品K随机排列,而不更换O(N)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!