Sample 'n' elements without replacement from the set [0..N-1]. This is an implementation of "Algorithm R" by J. Vitter.
| 58 | /// Sample 'n' elements without replacement from the set [0..N-1]. |
| 59 | /// This is an implementation of "Algorithm R" by J. Vitter. |
| 60 | void SampleN(int n, int N, vector<int>* out) { |
| 61 | if (n == 0) return; |
| 62 | DCHECK(n <= N); |
| 63 | out->reserve(n); |
| 64 | out->clear(); |
| 65 | for (int i = 0; i < n; ++i) out->push_back(i); |
| 66 | for (int i = n; i < N; ++i) { |
| 67 | // Accept element with probability n/i. Place at random position. |
| 68 | int r = rand() % i; |
| 69 | if (r < n) (*out)[r] = i; |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Sample a set of 'n' elements from 'in' without replacement and copy them to |
| 74 | /// 'out'. |
no test coverage detected