Skip to content

Instantly share code, notes, and snippets.

@christophfeinauer
christophfeinauer / selfpairs.jl
Last active June 7, 2016 16:39
Iterate over all pairs in an array (excluding combining elements with themselves)
import Base: start, next, done, eltype, length, size
immutable SelfPairs
xs
n::Int
end
eltype(it::SelfPairs) = eltype(it.xs)
length(it::SelfPairs) = binomial(it.n,2)
@christophfeinauer
christophfeinauer / random_element_from_dict.jl
Created June 6, 2016 12:38
Get a random key-value pair from a Julia dictionary
import Base: GLOBAL_RNG, rand, isslotfilled
function rand(rng::AbstractRNG, d::Dict)
isempty(d) && throw(ArugmentError("dictionary must be non-empty"))
n = length(d.keys)
while true
i = rand(rng,1:n)
!isdefined(d.keys,i) && continue
return d.keys[i],d.vals[i]
end
end