select m objects from n objects randomly

Q: how to select m objects randomly from n objects with euqal possibility?

A: allocate an array of m elements to keep the final result.

    put the first m objects into the array.

  foreach object k numbered from m+1 to n, generate an random rational number a in [0, 1],

     if a <= m/k then

    generate an random integer number in [1, m], say i, remove the i-th element from the final result,

           and put the kth number into it.

 

//PROVE the answer.

We can use mathematics induction.

The propositonal statement is P(n): the method in the answer can be used to select m objects out of n objects randomly, and each object is picked out with possibility of m/n, (n>=m).

Basis step:

P(m) is true since the answer put the first m elemets into the final result.

induction step:

The induction hypothesis is P(k) is true for all k>=m, then

the (k+1)-th element will be select with possibility of m/(k+1).

Any element kept in the final result before iteration k+1 has a possibility to be removed from the array which is m/(k+1) * (1/m), from the hypothesis, so it will stay in the final result with a possibility of m/k * (1 - m/(k+1) * (1/m)) = m/(k+1).

 

From the basis step and induction step, we have that P(n) is true for any integer n>=m.

 

 

 

转载于:https://www.cnblogs.com/Torstan/p/3489757.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值