首页 > 其他 > 详细

reservoir sampling / random shuffle

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!