In `StatsBase.jl`, is it possible for `sample` to not return vectors?

In StatsBase.jl, using sample function with many samples returns a vector with all the sample results. I might be overlooking the documents, but I’m looking for a way to “consume” each sample result in-place without building the resulting vector, while still enjoying the benefit of preprocessing. My use case is similar to the following:

nitems = 100
nsamples = 10000
w = Weights(rand(nitems))
counts = zeros(nitems)

# Is it possible to not generate the 10000-element intermediate vector?
for eachsample in sample(1:nitems, w, nsamples)
    counts[eachsample] += 1
end

# Alternatively, this seems not to utilize preprocessing.
for _ in 1:nsamples
    counts[sample(1:nitems, w)] += 1
end

Is there a way to achieve it? Thank you!

Have you considered the sample! function? Sampling from Population · StatsBase.jl!

This function reuses a single pre-allocated output array. But you’ll need one allocation still.

1 Like

Thanks! Indeed, that function also requires an array with the size of output. It is still beneficial if I want to do such sampling multiple times as I can reuse the buffer.