Skip to content

Commit e883d95

Browse files
committed
add rand(::Tuple)
1 parent 19b8c25 commit e883d95

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

stdlib/Random/src/generation.jl

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -429,3 +429,53 @@ function rand(rng::AbstractRNG, sp::SamplerSimple{<:AbstractString,<:Sampler})::
429429
isvalid_unsafe(str, pos) && return str[pos]
430430
end
431431
end
432+
433+
434+
## random elements from tuples
435+
436+
### 1
437+
438+
Sampler(::AbstractRNG, t::Tuple{A}, ::Repetition) where {A} =
439+
SamplerTrivial(t)
440+
441+
rand(rng::AbstractRNG, sp::SamplerTrivial{Tuple{A}}) where {A} =
442+
@inbounds return sp[][1]
443+
444+
### 2
445+
446+
Sampler(rng::AbstractRNG, t::Tuple{A,B}, n::Repetition) where {A,B} =
447+
SamplerSimple(t, Sampler(rng, Bool, n))
448+
449+
rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B}}) where {A,B} =
450+
@inbounds return sp[][1 + rand(rng, sp.data)]
451+
452+
### 3
453+
454+
Sampler(rng::AbstractRNG, t::Tuple{A,B,C}, n::Repetition) where {A,B,C} =
455+
SamplerSimple(t, Sampler(rng, UInt52(), n))
456+
457+
function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C}}) where {A,B,C}
458+
local r
459+
while true
460+
r = rand(rng, sp.data)
461+
r != 0x000fffffffffffff && break
462+
end
463+
@inbounds return sp[][1 + r ÷ 0x0005555555555555]
464+
end
465+
466+
### 4
467+
Sampler(rng::AbstractRNG, t::Tuple{A,B,C,D}, n::Repetition) where {A,B,C,D} =
468+
SamplerSimple(t, Sampler(rng, UInt52(), n))
469+
470+
function rand(rng::AbstractRNG, sp::SamplerSimple{Tuple{A,B,C,D}}) where {A,B,C,D}
471+
r = rand(rng, UInt52Raw(Int)) & 3
472+
@inbounds return sp[][1 + r]
473+
end
474+
475+
### n
476+
477+
Sampler(rng::AbstractRNG, t::Tuple, n::Repetition) =
478+
SamplerSimple(t, Sampler(rng, Base.OneTo(length(t)), n))
479+
480+
rand(rng::AbstractRNG, sp::SamplerSimple{<:Tuple}) =
481+
@inbounds return sp[][rand(rng, sp.data)]

stdlib/Random/test/runtests.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,3 +672,12 @@ end
672672
r = T(1):T(108)
673673
@test rand(RNG, SamplerRangeFast(r)) r
674674
end
675+
676+
@testset "rand(::Tuple)" begin
677+
@test rand((0x1,)) == 0x1
678+
@test rand((0x1, 2)) 1:2
679+
@test rand((0x1, 2, 3)) 1:3
680+
@test rand((0x1, 2, 3, 4)) 1:4
681+
@test rand((0x1, 2, 3, 4, 5)) 1:5
682+
@test rand((0x1, 2, 3, 4, 6)) 1:6
683+
end

0 commit comments

Comments
 (0)