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)dom

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

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;
    }
相關文章
相關標籤/搜索