Adapted from `ProbSampleReplace` Index version
| 79 | // Adapted from `ProbSampleReplace` |
| 80 | // Index version |
| 81 | inline 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 |
| 113 | template <int RTYPE> |