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

add shuffle(::NTuple) to Random #56906

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

nsajko
Copy link
Contributor

@nsajko nsajko commented Dec 26, 2024

Fixes #56728

@nsajko nsajko added randomness Random number generation and the Random stdlib stdlib Julia's standard library feature Indicates new feature / enhancement requests labels Dec 26, 2024
Comment on lines +186 to +206
function _tuple_without_element_at_index(tup::(Tuple{T, Vararg{T, N}} where {T}), i::Int) where {N}
clo = let tup = tup, i = i
function closure(j::Int)
k = if j < i
j
else
j + 1
end
tup[k]
end
end
ntuple(clo, Val{N}())
end

function shuffle(rng::AbstractRNG, tup::(Tuple{Vararg{T, N}} where {T})) where {N}
if tup isa Tuple{Any, Vararg}
let i = rand(rng, Base.OneTo(N)) # Fisher–Yates shuffle
s = _tuple_without_element_at_index(tup, i)
t = shuffle(rng, s)
(tup[i], t...)
end
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's also possible to rely on Memory getting stack-allocated, avoiding recursion:

Suggested change
function _tuple_without_element_at_index(tup::(Tuple{T, Vararg{T, N}} where {T}), i::Int) where {N}
clo = let tup = tup, i = i
function closure(j::Int)
k = if j < i
j
else
j + 1
end
tup[k]
end
end
ntuple(clo, Val{N}())
end
function shuffle(rng::AbstractRNG, tup::(Tuple{Vararg{T, N}} where {T})) where {N}
if tup isa Tuple{Any, Vararg}
let i = rand(rng, Base.OneTo(N)) # Fisher–Yates shuffle
s = _tuple_without_element_at_index(tup, i)
t = shuffle(rng, s)
(tup[i], t...)
end
function shuffle(rng::AbstractRNG, tup::(Tuple{Vararg{T, N}} where {T})) where {N}
if tup isa Tuple{Any, Vararg}
@inline let # `@inline` and `@inbounds` are here to help escape analysis
clo = @inbounds let mem = Memory{UInt16}(undef, N) # use `UInt16` to save stack space/prevent heap allocation
copyto!(mem, Base.OneTo(N))
shuffle!(mem)
let mem = mem, tup = tup
function closure(i::Int)
@inbounds tup[mem[i]]
end
end
end
ntuple(clo, Val{N}())
end

This suggestion depends on #56847 getting merged first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Indicates new feature / enhancement requests randomness Random number generation and the Random stdlib stdlib Julia's standard library
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Support shuffle(::NTuple)
1 participant