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

unify shuffle and randperm #50318

Merged
merged 3 commits into from
Jul 11, 2023
Merged
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
49 changes: 26 additions & 23 deletions stdlib/Random/src/misc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -201,34 +201,35 @@ julia> rng = MersenneTwister(1234);

julia> shuffle!(rng, Vector(1:16))
16-element Vector{Int64}:
2
15
5
14
16
1
9
14
12
5
10
6
11
4
15
13
3
16
7
4
12
9
6
11
8
13
2
```
"""
function shuffle!(r::AbstractRNG, a::AbstractArray)
# keep it consistent with `randperm!` and `randcycle!` if possible
require_one_based_indexing(a)
n = length(a)
n <= 1 && return a # nextpow below won't work with n == 0
@assert n <= Int64(2)^52
mask = nextpow(2, n) - 1
for i = n:-1:2
(mask >> 1) == i && (mask >>= 1)
n == 0 && return a
mask = 3
@inbounds for i = 2:n
j = 1 + rand(r, ltm52(i, mask))
a[i], a[j] = a[j], a[i]
i == 1 + mask && (mask = 2 * mask + 1)
end
return a
end
Expand All @@ -249,16 +250,16 @@ julia> rng = MersenneTwister(1234);

julia> shuffle(rng, Vector(1:10))
10-element Vector{Int64}:
6
1
10
2
3
1
7
9
5
7
10
4
8
6
3
```
"""
shuffle(r::AbstractRNG, a::AbstractArray) = shuffle!(r, copymutable(a))
Expand Down Expand Up @@ -315,6 +316,7 @@ julia> randperm!(MersenneTwister(1234), Vector{Int}(undef, 4))
```
"""
function randperm!(r::AbstractRNG, a::Array{<:Integer})
# keep it consistent with `shuffle!` and `randcycle!` if possible
n = length(a)
@assert n <= Int64(2)^52
n == 0 && return a
Expand All @@ -326,7 +328,7 @@ function randperm!(r::AbstractRNG, a::Array{<:Integer})
a[i] = a[j]
end
a[j] = i
i == 1+mask && (mask = 2mask + 1)
i == 1 + mask && (mask = 2 * mask + 1)
ctarn marked this conversation as resolved.
Show resolved Hide resolved
end
return a
end
Expand Down Expand Up @@ -382,16 +384,17 @@ julia> randcycle!(MersenneTwister(1234), Vector{Int}(undef, 6))
```
"""
function randcycle!(r::AbstractRNG, a::Array{<:Integer})
# keep it consistent with `shuffle!` and `randperm!` if possible
n = length(a)
n == 0 && return a
@assert n <= Int64(2)^52
n == 0 && return a
a[1] = 1
mask = 3
@inbounds for i = 2:n
j = 1 + rand(r, ltm52(i-1, mask))
a[i] = a[j]
a[j] = i
i == 1+mask && (mask = 2mask + 1)
i == 1 + mask && (mask = 2 * mask + 1)
end
return a
end
Expand Down