Skip to content

Commit

Permalink
shuffle: allow multidimensional arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
rfourquet committed Jun 5, 2017
1 parent 9f61fda commit 057c58f
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 9 deletions.
16 changes: 8 additions & 8 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1480,12 +1480,12 @@ randsubseq(A::AbstractArray, p::Real) = randsubseq(GLOBAL_RNG, A, p)
end

"""
shuffle!([rng=GLOBAL_RNG,] v)
shuffle!([rng=GLOBAL_RNG,] v::AbstractArray)
In-place version of [`shuffle`](@ref): randomly permute the array `v` in-place,
In-place version of [`shuffle`](@ref): randomly permute `v` in-place,
optionally supplying the random-number generator `rng`.
"""
function shuffle!(r::AbstractRNG, a::AbstractVector)
function shuffle!(r::AbstractRNG, a::AbstractArray)
n = length(a)
@assert n <= Int64(2)^52
mask = nextpow2(n) - 1
Expand All @@ -1497,18 +1497,18 @@ function shuffle!(r::AbstractRNG, a::AbstractVector)
return a
end

shuffle!(a::AbstractVector) = shuffle!(GLOBAL_RNG, a)
shuffle!(a::AbstractArray) = shuffle!(GLOBAL_RNG, a)

"""
shuffle([rng=GLOBAL_RNG,] v)
shuffle([rng=GLOBAL_RNG,] v::AbstractArray)
Return a randomly permuted copy of `v`. The optional `rng` argument specifies a random
number generator (see [Random Numbers](@ref)).
To permute `v` in-place, see [`shuffle!`](@ref). To obtain randomly permuted
To permute `v` in-place, see [`shuffle!`](@ref). To obtain randomly permuted
indices, see [`randperm`](@ref).
"""
shuffle(r::AbstractRNG, a::AbstractVector) = shuffle!(r, copymutable(a))
shuffle(a::AbstractVector) = shuffle(GLOBAL_RNG, a)
shuffle(r::AbstractRNG, a::AbstractArray) = shuffle!(r, copymutable(a))
shuffle(a::AbstractArray) = shuffle(GLOBAL_RNG, a)

"""
randperm([rng=GLOBAL_RNG,] n::Integer)
Expand Down
3 changes: 2 additions & 1 deletion test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,8 @@ let mta = MersenneTwister(42), mtb = MersenneTwister(42)
@test shuffle(mta,collect(1:10)) == shuffle(mtb,collect(1:10))
@test shuffle!(mta,collect(1:10)) == shuffle!(mtb,collect(1:10))
@test shuffle(mta,collect(2:11)) == shuffle(mtb,2:11)

@test shuffle!(mta, rand(mta, 2, 3)) == shuffle!(mtb, rand(mtb, 2, 3))
@test shuffle(mta, rand(mta, 2, 3)) == shuffle(mtb, rand(mtb, 2, 3))
@test randperm(mta,10) == randperm(mtb,10)
@test sort!(randperm(10)) == sort!(shuffle(1:10)) == collect(1:10)
@test randperm(mta,big(10)) == randperm(mtb,big(10)) # cf. #16376
Expand Down

0 comments on commit 057c58f

Please sign in to comment.