MCPcopy Create free account
hub / github.com/RcppCore/Rcpp / SampleNoReplace

Function SampleNoReplace

inst/include/Rcpp/sugar/functions/sample.h:255–291  ·  view source on GitHub ↗

Adapted from `ProbSampleNoReplace` Index version

Source from the content-addressed store, hash-verified

253// Adapted from `ProbSampleNoReplace`
254// Index version
255inline Vector<INTSXP> SampleNoReplace(Vector<REALSXP>& p, int n, int nans, bool one_based)
256{
257 Vector<INTSXP> perm = no_init(n), ans = no_init(nans);
258 double rT, mass, totalmass;
259 int i, j, k, n1;
260
261 int adj = one_based ? 0 : 1;
262
263 for (i = 0; i < n; i++) {
264 perm[i] = i + 1;
265 }
266
267 Rf_revsort(p.begin(), perm.begin(), n);
268
269 totalmass = 1.0;
270 for (i = 0, n1 = n - 1; i < nans; i++, n1--) {
271 rT = totalmass * unif_rand();
272 mass = 0.0;
273
274 for (j = 0; j < n1; j++) {
275 mass += p[j];
276 if (rT <= mass) {
277 break;
278 }
279 }
280
281 ans[i] = perm[j] - adj;
282 totalmass -= p[j];
283
284 for (k = j; k < n1; k++) {
285 p[k] = p[k + 1];
286 perm[k] = perm[k + 1];
287 }
288 }
289
290 return ans;
291}
292
293// Element version
294template <int RTYPE>

Callers 1

sampleFunction · 0.85

Calls 4

no_initFunction · 0.85
unif_randFunction · 0.85
beginMethod · 0.45
sizeMethod · 0.45

Tested by

no test coverage detected