Problems:
It is fairly simple: we have a list of numbers $x_1, x_2, \ldots,x_n,\ldots, x_m$. Our goal is to randomly and uniformly choose a subset of $n$ many numbers out of these.
This means that, for any $i \in \{1,2,\ldots,n,\ldots,m\}$, the probability of choosing the value of $x_i$ must be: $$ n\frac{1}{m} = \frac{n}{m} $$
An algorithm:
An instruction is $\text{swap}(x_{\text{left}},x_{\text{right}})$. It simply swaps their values. I.e.
- $t := x_{\text{left}}$
- $x_{\text{left}} := x_{\text{right}}$
- $x_{\text{right}} := t$
A suggested algorithm is: for each $i \in \{1,2,\ldots,n\}$, randomly and uniformly choose some $k_i \in \{1,2,\ldots,n, \ldots, m\}$, and then execute $\text{swap}(x_i, x_{k_i})$. Then return $x_1, x_2, \ldots, x_n$ as the set of $n$-many chosen numbers.
The challenge:
Intuitively, that algorithm looks to me to be perfectly fine. I see absolutely no problem in it.
But when I try to look at it mathematically, I fail to prove it. Instead, I actually seem to be prove that it is not a correct solution!
First, let's look at the probability of choosing the first $n$ numbers:
For any $i \in \{1,2,\ldots,n\}$, $x_i$ can be chosen if:
- $x_i$ exists in the right hand of $\text{swap}$. There are exactly $n$ cases, including the case when $x_i$ exists in, both, the left and the right hands.
- $x_i$ exists in the left hand, such that there exists $x_j$ in the right hand such that $j \in \{1,2,\ldots,n\}$. There are exactly $n$ such cases, one of which is the case when $i=j$ which we have counted earlier. Therefore, to avoid counting the case of $i=j$ twice, we assume that there are $n-1$ cases.
There is no other case where $x_i$ is chosen. Therefore the probability of choosing a number $x_i$, given that $i \in \{1,2,\ldots,n\}$ is: $$ \frac{n + (n-1)}{m^2} $$
Now, let's look at the probability of choosing the reset of the numbers up to $m$:
For any $i \in \{n+1,n+2,\ldots,m\}$, $x_i$ can be chosen if:
- $x_i$ exists in the right hand, such that there exists $x_j$ in the right hand such that $j \in \{1,2,\ldots,n\}$. There are exactly $n$ such cases.
There is no other case of having $x_i$ chosen. So the probability of choosing $x_i$ is: $$ \frac{n}{m^2} $$
Comparing the probabilities:
That says that there is a bias. The probability of choosing the 1st $n$ numbers is higher than the probability of choosing the reset of the numbers up to the $m^{th}$
My question:
Where did I go wrong? How to address this problem?