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
In The Practice of Programming, pg. 70, (The Markov Chain Algorithm) there is a similar algorithm for that:
[...]
nmatch = 0;
for ( /* iterate list */ )
if (rand() % ++nmatch == 0) /* prob = 1/nmatch */
w = suf->word;
[...]
"Notice the algorithm for selecting one item at random when we don't know how many items there are. The variable nmatch counts the number of matches as the list is scanned. The expression
rand() % ++nmatch == 0increments nmatch and is then true with probability 1/nmatch."