From 057c58f6e0e78ca29232ec765892f6bffbe8ebb6 Mon Sep 17 00:00:00 2001 From: Rafael Fourquet Date: Mon, 5 Jun 2017 16:11:48 +0200 Subject: [PATCH] shuffle: allow multidimensional arrays --- base/random.jl | 16 ++++++++-------- test/random.jl | 3 ++- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/base/random.jl b/base/random.jl index 29d2d842cc43d..649e42594ace6 100644 --- a/base/random.jl +++ b/base/random.jl @@ -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 @@ -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) diff --git a/test/random.jl b/test/random.jl index 79bbc7ecb2126..02b9ca5bb6354 100644 --- a/test/random.jl +++ b/test/random.jl @@ -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