This is a homework question. In order to print M sorted distinct random integers in range [0,N) we can use the following algo开发者_运维知识库rithm:
As we know, this algorithm pick all integers in the range with equal probability. Could you help me to prove it ?
int n = N
int m = M
for i in [0,N)
if (bigrandom() % n--) < m)
print i
m--
- The chance of having any particular number selected is
m/n
. - If this number is selected, we have same problem, but with
n' = n - 1
andm' = m - 1
. If it's not, we have same problem, but withn' = n - 1
andm' = m
.
Your algorithm is an implementation of this idea.
You'll also need to prove assumption 1
, but that you can probably do yourself.
精彩评论