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

Function SampleReplace

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

Adapted from `ProbSampleReplace` Index version

Source from the content-addressed store, hash-verified

79// Adapted from `ProbSampleReplace`
80// Index version
81inline Vector<INTSXP> SampleReplace(Vector<REALSXP>& p, int n, int k, bool one_based)
82{
83 Vector<INTSXP> perm = no_init(n), ans = no_init(k);
84 double rU = 0.0;
85 int i = 0, j = 0, nm1 = n - 1;
86
87 int adj = one_based ? 0 : 1;
88
89 for ( ; i < n; i++) {
90 perm[i] = i + 1;
91 }
92
93 Rf_revsort(p.begin(), perm.begin(), n);
94
95 for (i = 1; i < n; i++) {
96 p[i] += p[i - 1];
97 }
98
99 for (i = 0; i < k; i++) {
100 rU = unif_rand();
101 for (j = 0; j < nm1; j++) {
102 if (rU <= p[j]) {
103 break;
104 }
105 }
106 ans[i] = perm[j] - adj;
107 }
108
109 return ans;
110}
111
112// Element version
113template <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