Reservoir sampling

Having an input stream of n, select k elements with equal probability.


Algorithm: 

1. select k elements into the result first 0....k-1

2. for k....n-1 elements, each time i, generate a random number 0....i: if rand < k, set result[k] = input[i]


Prove: http://www.geeksforgeeks.org/reservoir-sampling/

1. For elements k....n-1

a) The last element  n-1, has k/n chance to be selected

b) The second last element n-2, in the first has k/n-1 chance to be selected to the k result; and when we iterate to the last element, that second last element has (n-1)/n chance to be NOT swapped back to the rest input. Total k/(n-1) * (n-1)/n = k/n

2. For elements 0...k-1

Each time the m (0<=m<=k-1) is not swapped chance: k/(k+1) * (k+1)/(k+2)....(n-1/n = k/n

How to generate the random number:

1) use Math.rand() which generate 0....0.99999, to get a rand between 0-i, use (int)(Math.rand() * (i+1))

2) use Random.nextInt(i) which generate 0....i-1 integers

    public static int[] sample(int[] input, int k) {
        int[] result = new int[k];
        int i = 0;
        for (; i < k; i++) {
            result[i] = input[i];
        }
        Random random = new Random();
        for (; i < input.length; i++) {
//            int rand = (int) (Math.random() * (i+1));
          int rand = random.nextInt(i+1);
            if (rand < k) {
                result[rand] = input[i];
            }
        }
        return result;
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值