Suppose I have a list, called elements
, each of which does or does not satisfy some boolean property p
. I want to choose one of the elements that satisfies p
by random with uniform distribution. I do not know ahead of time how many items satisfy this property p
.
Will the following code do this?:
pickRandElement(elements, p)
randElement = null
count = 0
foreach element in elements
if (p(element))
count = count + 1
if (randInt(count) == 0)
randElement = element
return randElement
(randInt(n)
returns a random int k
with 0 <= k < n
.)