Dear all,<br><br>Code for uniform sampling is below, following the prototype from earlier post. Results/unit-tests (not included) are identical to R-core sample().<br><br>-Christian<br><br><div>template <class T> <br>
T sample(const T &x, const unsigned int size, const bool replace ) {<br> int ii, jj;<br> int nOrig = x.size();<br> T ret(size);<br> if ( size > nOrig && !replace) throw std::range_error( "Tried to sample more elements than in x without replacement" ) ;<br>
IntegerVector index(size);<br> if (replace) {<br> SampleReplace(index, nOrig);<br> } else {<br> SampleNoReplace(index, nOrig);<br> }<br><br> for (ii=0; ii<size; ii++) {<br> jj = index[ii];<br>
ret[ii] = x[jj];<br> }<br> return(ret);<br>}<br><br>void SampleReplace( IntegerVector index, unsigned int nOrig) {<br> int ii;<br> int nSample = index.size();<br> for (ii = 0; ii < nSample; ii++) {<br>
index[ii] = nOrig * unif_rand();<br> }<br>}<br><br>void SampleNoReplace( IntegerVector index, unsigned int nOrig) {<br> int ii, jj;<br> int nSample = index.size();<br> IntegerVector sub(nOrig);<br> for (ii = 0; ii < nOrig; ii++) {<br>
sub[ii] = ii;<br> }<br><br> for (ii = 0; ii < nSample; ii++) {<br> jj = nOrig * unif_rand();<br> index[ii] = sub[jj];<br> // replace sampled element with last, decrement<br> sub[jj] = sub[--nOrig];<br>
}<br>}<br></div>