You can also use Distributions
and rand
julia> using Distributions
julia> a = Categorical([0.2, 0.2, 0.2, 0.2, 0.2])
DiscreteNonParametric{Int64,Float64,Base.OneTo{Int64},Array{Float64,1}}(
support: Base.OneTo(5)
p: [0.2, 0.2, 0.2, 0.2, 0.2]
)
julia> rand(a)
3
rand(a
) returns the index of the array with that probability.
If it matters,
julia> @time sample(1:5, ProbabilityWeights([0.2, 0.2, 0.2, 0.2, 0.2]))
0.000016 seconds (7 allocations: 352 bytes)
julia> @time rand(a)
0.000005 seconds (4 allocations: 160 bytes)