码迷,mamicode.com
首页 > 其他好文 > 详细

reservoir sampling / random shuffle

时间:2016-10-28 02:30:32      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:get   item   mil   shuffle   wap   for   ons   tar   put   

randomly choose a sample of k items from a list S containing n elements, the algorithm may be online (i.e. the input list is unknown beforehand)

https://en.wikipedia.org/wiki/Reservoir_sampling

ReserviorSampling(Source[1..n], Result[1..k]) {
    for (int i = 1; i <= k; i++) {
        Result[i] = Source[i];
    }
    for (int i = k+1; i <= n; i++) {
        int rand = Random.get(1, i); // both 1 and i are inclusive
        if (rand <= k) {
            Result[rand] = Source[i];
        }
    }
    return Result;
}

 

    vector<int> shuffle(const vector<int> &nums) {
        auto ret = nums;
        int n = ret.size();
        for (int i = 0; i < n; i++) {
            int s = rand()%(n-i)+i;
            swap(ret[i], ret[s]);
        }
        return ret;
    }

 

reservoir sampling / random shuffle

标签:get   item   mil   shuffle   wap   for   ons   tar   put   

原文地址:http://www.cnblogs.com/qsort/p/6006084.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!