How to get a random element from a Set? Or in general, from a non-indexable 
collection?

Obviously A[rand(1:length(A))] doesn't work (where A is the Set). I tried 
this:

function rand{T}(s::Set{T})
    @assert !isempty(s)
    k = rand(1:length(s))
    for x in s
        k -= 1
        if k == 0; return x end
    end
end

But this is O(n), where n is the length of the set. Is there a more 
efficient way?

Reply via email to