Vector of random integers where each integer occurs 10 times C++

58 views Asked by At
#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    // First create an instance of an engine.
    random_device rnd_device;
    // Specify the engine and distribution.
    mt19937 mersenne_engine {rnd_device()};  // Generates random integers
    uniform_int_distribution<int> dist {0, 2};
    
    auto gen = [&dist, &mersenne_engine](){
                   return dist(mersenne_engine);
               };

    vector<int> vec(30);
    generate(begin(vec), end(vec), gen);
    
    // Optional
    for (auto i : vec) {
        cout << i << " ";
    }
    

}

I am trying to create a vector of 30 numbers consisting of values 0-2 and each integer occurs 10 times. What is the most efficient way to do this in C++.

1

There are 1 answers

0
A M On

Basically it should be done as written in the comments.

  • First we define a std::vector with the given size
  • Then, we fill it with an ultra simple Lambda
  • And finally we shuffle it

The resulting code is simple and efficient. Please see:

#include <random>
#include <algorithm>
#include <iterator>
#include <iostream>
#include <vector>

int main() {
    // Engine to shuffle the vector    
    std::random_device rnd_device;
    std::mt19937 me{ rnd_device() };  

    // Simple filler lambda
    auto filler = [n = 0]() mutable->int { return n++ / 10; };
 
    // Define vector with given size
    std::vector<int> vec(30);

    // Fill and shuffle
    std::generate(vec.begin(), vec.end(), filler);
    std::shuffle(vec.begin(), vec.end(), me);

    // Debug output
    std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
}