how to select M numbers from N existing numbers randomly and fairly (N>M). Example, assume that there are 10 numbers, you need to select 3 numbers from them randomly.
take 8 numbers, select one number from these 8 numbers, but not take away this number
add one number to the set, select one number from set, if the number is the selected number, just select the new added number.
add one number to the set, select one number from set, if the number is the selected number, just select the new added number
for the 8 numbers the probability of not chosen is 7/8 * 8/9 * 9/10=7/10
for the 9th number, the probability of not chosen is 7/9*9/10=7/10
for the 10th number, the probability of not chosen is 7/10
A={}
for(int i=n-m+1;i<=n;++i)
{
int a=rand()%i+1;
if(a is not in A)
A=A+{a};
else A=A+{i};
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment