diff --git a/base/random.jl b/base/random.jl index 07f1b833d7d6e..187c1ffe03b48 100644 --- a/base/random.jl +++ b/base/random.jl @@ -369,7 +369,10 @@ function rand{T<:Integer, U<:Unsigned}(g::RandIntGen{T,U}) end rand{T<:Union(Signed,Unsigned,Bool,Char)}(r::UnitRange{T}) = rand(RandIntGen(r)) -rand{T}(r::Range{T}) = r[rand(1:(length(r)))] + +# Randomly draw a sample from an AbstractArray r +# (e.g. r is a range 0:2:8 or a vector [2, 3, 5, 7]) +rand(r::AbstractArray) = @inbounds return r[rand(1:length(r))] function rand!(g::RandIntGen, A::AbstractArray) for i = 1 : length(A) @@ -380,7 +383,10 @@ end rand!{T<:Union(Signed,Unsigned,Bool,Char)}(r::UnitRange{T}, A::AbstractArray) = rand!(RandIntGen(r), A) -function rand!(r::Range, A::AbstractArray) +rand!(r::Range, A::AbstractArray) = _rand!(r, A) + +# TODO: this more general version is "disabled" until #8246 is resolved +function _rand!(r::AbstractArray, A::AbstractArray) g = RandIntGen(1:(length(r))) for i = 1 : length(A) @inbounds A[i] = r[rand(g)] @@ -388,8 +394,8 @@ function rand!(r::Range, A::AbstractArray) return A end -rand{T}(r::Range{T}, dims::Dims) = rand!(r, Array(T, dims)) -rand(r::Range, dims::Int...) = rand(r, dims) +rand{T}(r::AbstractArray{T}, dims::Dims) = _rand!(r, Array(T, dims)) +rand(r::AbstractArray, dims::Int...) = rand(r, dims) ## random BitArrays (AbstractRNG) diff --git a/doc/stdlib/base.rst b/doc/stdlib/base.rst index d9d4fb5bc983a..271dc317987bd 100644 --- a/doc/stdlib/base.rst +++ b/doc/stdlib/base.rst @@ -4028,9 +4028,13 @@ A ``MersenneTwister`` RNG can generate random numbers of the following types: `` Populate the array A with random values. -.. function:: rand(r, [dims...]) +.. function:: rand(coll, [dims...]) - Pick a random element or array of random elements from range ``r`` (for example, ``1:n`` or ``0:2:10``). + Pick a random element or array of random elements from the indexable collection ``coll`` (for example, ``1:n`` or ``['x','y','z']``). + +.. function:: rand!(r, A) + + Populate the array A with random values drawn uniformly from the range ``r``. .. function:: randbool([rng], [dims...]) diff --git a/test/random.jl b/test/random.jl index ab871c2e7f4fe..96a52746ee53d 100644 --- a/test/random.jl +++ b/test/random.jl @@ -31,6 +31,12 @@ rand!(MersenneTwister(0), A) @test A == [858542123778948672 5715075217119798169; 8690327730555225005 8435109092665372532] +# rand from AbstractArray +@test rand(0:3:1000) in 0:3:1000 +coll = Any[2, UInt128(128), big(619), "string", 'c'] +@test rand(coll) in coll +@test issubset(rand(coll, 2, 3), coll) + # randn @test randn(MersenneTwister(42)) == -0.5560268761463861 A = zeros(2, 2)