首页 > 代码库 > reservoir sampling / random shuffle

reservoir sampling / random shuffle

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