Dear all,

I have a vector: `I = 1:55`

. I need to partition it into 10 subvectors, none of which must be empty and the length of each of which is a random number. What is the best way to do this? Could someone help me?

What is the use case? Do you have other constraints on the lengths? Why not take them constant?

I need different lenghts to insert in a optimization problem. Moreover, all components of ```I```` need to be used.

Okay but why do the lengths need to be different?

Do the subvectors need to be contiguous?

Here’s a simple code that does uniform assignment over the `k`

subvectors.

```
n, k = 55, 10
x = 1:n
select = rand(1:k, n)
subvectors = Vector{Vector{eltype(x)}}(undef, k)
for i in 1:k
subvectors[i] = x[select .== i]
end
```

Example result:

```
julia> subvectors
10-element Vector{Vector{Int64}}:
[4, 5, 6, 31, 46, 53]
[7, 17, 48]
[3, 16, 26, 39, 41, 51, 52]
[1, 10, 12, 13, 19, 21, 43, 54]
[]
[9, 28, 32, 37, 42]
[15, 23, 27, 30, 34, 40]
[2, 11, 20, 22, 38, 44, 47]
[8, 14, 24, 33, 36, 45, 50, 55]
[18, 25, 29, 35, 49]
```

If you want none of them to be empty, one way would be to assign the first `k`

elements of `x`

deterministically for instance.

1 Like

Thanks a lot!!!

Using the prototypical decomposition of 55 = 1+2+…+10, it seems you might be looking for something like:

```
julia> using Random
julia> shuffle(getindex.(Ref(shuffle(1:55)),(:).(cumsum(0:9).+1,cumsum(1:10))))
10-element Vector{Vector{Int64}}:
[29, 52, 30]
[5, 24, 28, 21, 27, 22]
[12, 38, 31, 26, 16, 23, 9, 36, 18]
[13, 45, 46, 34, 14, 41, 19, 10, 3, 4]
[8, 37, 7, 11]
[51, 6]
[54, 15, 40, 48, 20, 35, 50]
[17, 53, 1, 2, 44]
[39]
[42, 43, 49, 32, 33, 25, 55, 47]
```

There are a few optimizations still possible on this expression, but is this in the direction you are looking?