Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

shuffle: allow multidimensional arrays #22226

Merged
merged 1 commit into from
Jun 6, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions base/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1482,12 +1482,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 @@ -1499,18 +1499,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
2 changes: 2 additions & 0 deletions test/random.jl
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +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)
Expand Down