For concreteness, how would you read a text line and select and print one random line if you do not know the number of lines in advance?
Yes, this is a problem from the pearl of programming, with which I am confused.
The solution selects the 1st element, then select the second with a probability of 1/2, the third with 1/3, etc.
Algorithm:
i = 0 while more input lines with probability 1.0/++i choice = this input line print choice
Suppose the final choice is the third element, the probability is 1 x 1/2 x 1/3 x 3/4 x ... x n-2 / n-1 x n-1 / n == 1 / 2n? But 1 / n must be correct.
source share