Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random integers by group in julia

Tags:

julia

First, I would like to divide the intergers from 1 to n equally into m groups.

Second, I want to generate random intergers without replacement in each group by Julia.

Third, I would like to combine all the random integers.

For example, n=10000, m=2. Then the julia code would be

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

For example, n=10000, m=5. Then the julia code would be

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]

I am just wondering if I can improve the julia code above. If m=100. then my code will be extremely long. There must be an eaiser way to do this.

like image 571
Mizzle Avatar asked Nov 14 '21 21:11

Mizzle


Video Answer


1 Answers

Assume that you have eg. n=30 and m=5 (note that n % m == 0). Than you can create the place to hold the results named x:

x = collect(1:n);

And now you can do this one liner (this requires using Random):

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

Let us see the result (you have 5 groups and within each group values are randomly ordered without repetitions):

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
like image 175
Przemyslaw Szufel Avatar answered Oct 28 '22 19:10

Przemyslaw Szufel