How do I select a random item from a weighted array in Julia?

Use the StatsBase.jl package, i.e.

Pkg.add("StatsBase")  # Only do this once, obviously
using StatsBase
items = ["a", 2, 5, "h", "hello", 3]
weights = [0.1, 0.1, 0.2, 0.2, 0.1, 0.3]
sample(items, Weights(weights))

Or if you want to sample many:

# With replacement
my_samps = sample(items, Weights(weights), 10)
# Without replacement
my_samps = sample(items, Weights(weights), 2, replace=false)

(In Julia < 1.0, Weights was called WeightVec).

You can learn more about Weights and why it exists in the docs. The sampling algorithms in StatsBase are very efficient and designed to use different approaches depending on the size of the input.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)