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;
    }

 

相关文章:

  • 2021-12-26
  • 2021-08-25
  • 2021-07-22
  • 2021-10-06
  • 2022-12-23
  • 2021-07-11
猜你喜欢
  • 2022-12-23
  • 2022-01-10
  • 2022-01-22
  • 2021-07-06
  • 2022-12-23
  • 2021-10-22
相关资源
相似解决方案