diff --git a/stdlib/Random/src/misc.jl b/stdlib/Random/src/misc.jl index d24fe9c457ccf..19689613d387f 100644 --- a/stdlib/Random/src/misc.jl +++ b/stdlib/Random/src/misc.jl @@ -255,9 +255,12 @@ shuffle(a::AbstractArray) = shuffle(GLOBAL_RNG, a) randperm([rng=GLOBAL_RNG,] n::Integer) Construct a random permutation of length `n`. The optional `rng` -argument specifies a random number generator (see [Random Numbers](@ref)). -To randomly permute an arbitrary vector, see [`shuffle`](@ref) -or [`shuffle!`](@ref). +argument specifies a random number generator (see [Random +Numbers](@ref)). The element type of the result is the same as the type +of `n`. + +To randomly permute an arbitrary vector, see [`shuffle`](@ref) or +[`shuffle!`](@ref). # Examples ```jldoctest @@ -269,7 +272,7 @@ julia> randperm(MersenneTwister(1234), 4) 3 ``` """ -randperm(r::AbstractRNG, n::Integer) = randperm!(r, Vector{Int}(undef, n)) +randperm(r::AbstractRNG, n::T) where {T <: Integer} = randperm!(r, Vector{T}(undef, n)) randperm(n::Integer) = randperm(GLOBAL_RNG, n) """ @@ -317,6 +320,7 @@ randperm!(a::Array{<:Integer}) = randperm!(GLOBAL_RNG, a) Construct a random cyclic permutation of length `n`. The optional `rng` argument specifies a random number generator, see [Random Numbers](@ref). +The element type of the result is the same as the type of `n`. # Examples ```jldoctest @@ -330,7 +334,7 @@ julia> randcycle(MersenneTwister(1234), 6) 2 ``` """ -randcycle(r::AbstractRNG, n::Integer) = randcycle!(r, Vector{Int}(undef, n)) +randcycle(r::AbstractRNG, n::T) where {T <: Integer} = randcycle!(r, Vector{T}(undef, n)) randcycle(n::Integer) = randcycle(GLOBAL_RNG, n) """ diff --git a/stdlib/Random/test/runtests.jl b/stdlib/Random/test/runtests.jl index 83e4b44e83697..56318d3e2c162 100644 --- a/stdlib/Random/test/runtests.jl +++ b/stdlib/Random/test/runtests.jl @@ -485,18 +485,26 @@ let mta = MersenneTwister(42), mtb = MersenneTwister(42) @test sort!(randperm(10)) == sort!(shuffle(1:10)) == 1:10 @test randperm(mta,big(10)) == randperm(mtb,big(10)) # cf. #16376 @test randperm(0) == [] - @test eltype(randperm(UInt(1))) === Int @test_throws ErrorException randperm(-1) + let p = randperm(UInt16(12)) + @test typeof(p) ≡ Vector{UInt16} + @test sort!(p) == 1:12 + end + A, B = Vector{Int}(undef, 10), Vector{Int}(undef, 10) @test randperm!(mta, A) == randperm!(mtb, B) @test randperm!(A) === A @test randcycle(mta,10) == randcycle(mtb,10) - @test eltype(randcycle(UInt(1))) === Int @test randcycle!(mta, A) == randcycle!(mtb, B) @test randcycle!(A) === A + let p = randcycle(UInt16(10)) + @test typeof(p) ≡ Vector{UInt16} + @test sort!(p) == 1:10 + end + @test sprand(mta,1,1,0.9) == sprand(mtb,1,1,0.9) @test sprand(mta,10,10,0.3) == sprand(mtb,10,10,0.3) end