I'm reading about the reservoir sampling technique called Algorithm R.
The idea is we can take a sample of size $n$ from a population of size $N$ even when $N$ is unknown/too expensive to retrieve in $N$ time. I quote a sample implementation from wikipedia:
(* S has items to sample, R will contain the result *) ReservoirSample(S[1..n], R[1..k]) // fill the reservoir array for i = 1 to k R[i] := S[i] // replace elements with gradually decreasing probability for i = k+1 to n j := random(1, i) // important: inclusive range if j <= k R[j] := S[i]
The explanation for why this works:
The algorithm creates a "reservoir" array of size $k$ and populates it with the first $k$ items of $S$.
That is pretty clear, the first for loop in the code sample does that. Then:
It then iterates through the remaining elements of $S$ until $S$ is exhausted. At the $i$-th element of $S$, the algorithm generates a random number $j$ between $1$ and $i$. If $j$ is less than or equal to $k$, the $j$-th element of the reservoir array is replaced with the $i$-th element of $S$.
Also clear. But here comes the Math:
In effect, for all $i$, the $i$-th element of $S$ is chosen to be included in the reservoir with probability $\frac{k}{i}$.
Hmm, I'm probably not well versed enougn in probablility theory, so can someone explain in more detail how the probability is $\frac{k}{i}$?
What I also don't get: do all elements have the same chance of being included in the (final) reservoir? From my understanding, it seems like the probability decreases for the elements at the end of $S$ to be included, then the reservoir will be skewed towards including the earlier elements, or am I misled?