@@ -3,6 +3,7 @@ using DerivableInterfaces: DerivableInterfaces, @derive, @interface, AbstractArr
33# This is to bring `ArrayLayouts.zero!` into the namespace
44# since it is considered part of the sparse array interface.
55using ArrayLayouts: zero!
6+ using Random: Random, AbstractRNG, default_rng
67
78function eachstoredindex end
89function getstoredindex end
@@ -32,6 +33,48 @@ function densearray(a::AbstractArray)
3233 return Array(a)
3334end
3435
36+ @doc """
37+ sprand([rng], [T::Type], dims; density::Real) -> A::SparseArrayDOK{T}
38+
39+ Create a random size `dims` sparse array in which the probability of any element being stored is independently given by `density`.
40+ The optional `rng` argument specifies a random number generator, see also `Random`.
41+ The optional `T` argument specifies the element type, which defaults to `Float64`.
42+
43+ See also [`sprand!`](@ref).
44+ """ sprand
45+
46+ function sprand(:: Type{T} , dims:: Dims ; density:: Real = 0.5 ) where {T}
47+ return sprand(default_rng(), T, dims; density)
48+ end
49+ sprand(dims:: Dims ; density:: Real = 0.5 ) = sprand(default_rng(), Float64, dims; density)
50+ function sprand(rng:: AbstractRNG , dims:: Dims ; density:: Real = 0.5 )
51+ return sprand(rng, Float64, dims; density)
52+ end
53+ function sprand(rng:: AbstractRNG , :: Type{T} , dims:: Dims ; density:: Real = 0.5 ) where {T}
54+ A = SparseArrayDOK{T}(undef, dims)
55+ sprand!(rng, A; density)
56+ return A
57+ end
58+
59+ @doc """
60+ sprand!([rng], A::AbstractArray; density::Real=0.5) -> A
61+
62+ Overwrite part of an array with random entries, where the probability of overwriting is independently given by `density`.
63+ The optional `rng` argument specifies a random number generator, see also `Random`.
64+
65+ See also [`sprand`](@ref).
66+ """ sprand!
67+
68+ sprand!(A:: AbstractArray ; density:: Real = 0.5 ) = sprand!(default_rng(), A; density)
69+ function sprand!(rng:: AbstractRNG , A:: AbstractArray ; density:: Real = 0.5 )
70+ rand_inds = Random. randsubseq(rng, eachindex(A), density)
71+ rand_entries = rand(rng, eltype(A), length(rand_inds))
72+
73+ for (I, v) in zip(rand_inds, rand_entries)
74+ A[I] = v
75+ end
76+ end
77+
3578# Minimal interface for `SparseArrayInterface`.
3679# Fallbacks for dense/non-sparse arrays.
3780@interface :: AbstractArrayInterface isstored(a:: AbstractArray , I:: Int... ) = true
0 commit comments