Skip to content

Commit

Permalink
fast rand(::Dict) and rand(::Set) (#18155)
Browse files Browse the repository at this point in the history
fixes #16231
  • Loading branch information
dbeach24 authored and StefanKarpinski committed Aug 20, 2016
1 parent 6628674 commit 4f88b52
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,19 @@ function rand(r::AbstractRNG, ::Type{Char})
(c < 0xd800) ? Char(c) : Char(c+0x800)
end

# random values from Dict or Set (for efficiency)
function rand(r::AbstractRNG, t::Dict)
isempty(t) && throw(ArgumentError("dict must be non-empty"))
n = length(t.slots)
while true
i = rand(r, 1:n)
Base.isslotfilled(t, i) && return (t.keys[i] => t.vals[i])
end
end
rand(t::Dict) = rand(GLOBAL_RNG, t)
rand(r::AbstractRNG, s::Set) = rand(r, s.dict).first
rand(s::Set) = rand(GLOBAL_RNG, s)

## Arrays of random numbers

rand(r::AbstractRNG, dims::Dims) = rand(r, Float64, dims)
Expand Down
6 changes: 6 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ let mt = MersenneTwister()
rand(coll, 2, 3)
end

# rand using Dict, Set
adict = Dict(1=>2, 3=>4, 5=>6)
@test rand(adict) in adict
aset = Set(1:10)
@test rand(aset) in aset

# randn
@test randn(MersenneTwister(42)) == -0.5560268761463861
A = zeros(2, 2)
Expand Down

0 comments on commit 4f88b52

Please sign in to comment.