如何在Julia中按组生成随机整数

6

首先,我想将1到n的整数平均分成m组。

其次,我想用Julia在每个组中生成不重复的随机整数。

最后,我希望将所有随机整数组合起来。

例如,当n=10000,m=2时,Julia代码如下:

using Distributions
n=10000
order1 = sample(1:5000, 5000, replace = false)
order2 = sample(5001:10000, 5000, replace = false)
order=[order1;order2]

例如,n=10000,m=5。那么julia代码将如下所示:
using Distributions
n=10000
order1 = sample(1:2000, 2000, replace = false)
order2 = sample(2001:4000, 2000, replace = false)
order3 = sample(4001:6000, 2000, replace = false)
order4 = sample(6001:8000, 2000, replace = false)
order5 = sample(8001:10000, 2000, replace = false)
order=[order1;order2;order3;order4;order5]

我在想能否改进上面的Julia代码。如果m为100,则我的代码将非常冗长。肯定有更简便的方法。
1个回答

3
假设您有 n=30m=5,(请注意 n % m == 0)。 那么您可以创建一个名为 x 的结果容器:
x = collect(1:n);

现在你可以使用以下一行代码实现这个功能(需要 using Random):

shuffle!.(eachcol(reshape(x, n ÷ m, m)));

让我们看一下结果(你有5个组,每个组内的值都是随机排序而且不重复的):

julia> x'
1×30 adjoint(::Vector{Int64}) with eltype Int64:
 1  5  3  2  4  6  12  10  8  9  7  11  16  18  13  14  15  17  24  21  23  22  20  19  26  25  27  30  29  28

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接