[英]Generate an array of N random integers, between 1 and K, but containing at least one of each number
I need to generate a matrix of N
random integers between 1
and K
, where each number appears at least once, having K ≤ N
. 我需要生成一个介于
1
和K
之间的N
随机整数的矩阵,其中每个数字至少出现一次, K ≤ N
。
I have no problem using a call to numpy.random.random_integers()
and checking the number of distinct elements, when K
is much less than N
, but it's harder to get a valid array when K
approximates to N
. 当
K
远小于N
,我可以使用对numpy.random.random_integers()
的调用并检查不同元素的数量,但是当K
接近N
时,很难获得有效的数组。
Is there any nice way to get this done? 有什么好办法可以做到这一点吗? Any hint would be appreciated.
任何提示将不胜感激。
I don't think there's any built in functionality, but you could always make the exact array you want and shuffle/reshape. 我认为没有任何内置功能,但是您始终可以制作出想要的确切数组并进行随机播放/重塑。
Something like, 就像是,
raw_array = np.append(np.arange(1, K+1), np.random.randint(1, K+1, size=(N-K)))
np.random.shuffle(raw_array)
This guarantees you have 1 to K from your arange, then the remaining required numbers (N - K) are filled by a random number from 1 to K. 这样可以保证您的范围从1到K,然后剩余的所需数字(N-K)由1到K的随机数填充。
Edited to specifically get 1 through K, rather than 0 to K - 1. 编辑为专门通过K获得1,而不是0至K-1。
Fill the matrix iteratively with numbers 1-K so if K was 2, and N was 4, [1,2,1,2]. 用数字1-K迭代填充矩阵,所以如果K为2,N为4,则[1,2,1,2]。 Then randomly generate 2 random numbers between 1-N where the numbers don't equal, and swap the numbers at those positions.
然后在数字不相等的1-N之间随机生成2个随机数,并在这些位置交换数字。
使用xrange(k)填充K个数字,然后使用随机数生成器填充(nk)个数字
您正在寻找np.random.choice(N, size=K, replace=False)
doc ,它将返回K
不同的数字,最多N
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.