Broadcasting sampling of the variable size

I would like to use broadcast to do repetitive sampling from an array with the added twist that samples are of variable sizes. In plain English I would like to replace the following for loop with a fancy code

using StatsBase
myspace = 1:10
for j = 3:1:5
      println(sample(myspace,j; replace=false, ordered=true))
end

Any hints? This seems trivial but I can wrap my mind around it.

Maybe you’re looking for this:

julia> sample.(Ref(myspace), 3:5; replace=false, ordered=true)
3-element Vector{Vector{Int64}}:
 [4, 5, 7]
 [3, 4, 6, 10]
 [2, 3, 6, 9, 10]

Here I use Ref to “escape” myspace from broadcasting. If I write sample(myspace, 3:5) it will broadcast on both myspace and 3:5. Wrapping with Ref is like creating a container with one element, so it broadcasts on Ref(myspace) which has just a single value myspace in it.

Equivalently you could do

sample.((myspace,), 3:5; replace=false, ordered=true)

or

sample.([myspace], 3:5; replace=false, ordered=true)
1 Like