Skip to content

Commit 6d329ce

Browse files
committed
make rand work with AbstractArray instead of only with Range
This implements the generalization suggested by @ivarne (#8257 (comment)) or by @lindahua (#6003 (comment)). This change is very simple thanks to commit 48f27bc.
1 parent e2b14a1 commit 6d329ce

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

base/random.jl

+11-5
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,7 @@ rand{T<:Number}(::Type{T}) = error("no random number generator for type $T; try
146146
rand{T<:Number}(::Type{T}, dims::Int...) = rand(T, dims)
147147

148148

149-
## Generate random integer within a range
149+
## Generate random integer within a range 1:n
150150

151151
# remainder function according to Knuth, where rem_knuth(a, 0) = a
152152
rem_knuth(a::Uint, b::Uint) = a % (b + (b == 0)) + a * (b == 0)
@@ -208,18 +208,24 @@ function rand{T<:Integer, U<:Unsigned}(g::RandIntGen{T,U})
208208
itrunc(T, one(U) + rem_knuth(x, g.k))
209209
end
210210

211-
rand{T}(r::Range{T}) = r[rand(randintgen(length(r)))]
212211

213-
function rand!(r::Range, A::AbstractArray)
212+
## Randomly draw a sample from an AbstractArray r
213+
# (e.g. r is a range 0:2:8 or a vector [2, 3, 5, 7])
214+
215+
rand(r::AbstractArray) = r[rand(randintgen(length(r)))]
216+
217+
# Arrays of random integers
218+
219+
function rand!(r::AbstractArray, A::AbstractArray)
214220
g = randintgen(length(r))
215221
for i = 1 : length(A)
216222
@inbounds A[i] = r[rand(g)]
217223
end
218224
return A
219225
end
220226

221-
rand{T}(r::Range{T}, dims::Dims) = rand!(r, Array(T, dims))
222-
rand(r::Range, dims::Int...) = rand(r, dims)
227+
rand{T}(r::AbstractArray{T}, dims::Dims) = rand!(r, Array(T, dims))
228+
rand(r::AbstractArray, dims::Int...) = rand(r, dims)
223229

224230

225231
## random Bools

0 commit comments

Comments
 (0)