Random Sampling with Replacement

I draw a space here: how do you make a selection with a replacement in C++(without using boost), but all the members std::are fine. I mean, what is the approach (or function, if we can flip the element std::).

To provide some context, I want the samples (with replacement) kfrom the array Data[n]from to ndouble.

+4
source share
1 answer

If a function is specified random_num_in_range(more on this later), you should not roll your own sampler so hard:

// Samples randomly from (b, e) into o, n elements
template<typename It, typename OutIt>
void sample(It b, It e, OutIt o, size_t n)
{
    // Number of elements in range.
    const size_t s = std::distance(b, e);
    // Generate n samples.
    for(size_t i = 0; i < n; ++i)
    {
        It it = b;
        // Move b iterator random number of steps forward.
        std::advance(it, random_num_in_range(s));
        // Write into output
        *(o++) = *it;
    }
}

You could use it, perhaps like this:

vector<int> input;
...
vector<int> output;
sample(input.begin(), input.end(), back_inserter(output), 100);

, random_number_in_range . , ( , , - - ).

+3

Source: https://habr.com/ru/post/1629062/


All Articles