lundi 28 septembre 2015

Faster way then mine to populate a vector with unique integers except two values ? C++

I can´t post my all program here, just snippets. Will answer any question.

What I have:

1) I have a vector with 20 ID´s, like this [0,1,2,3,4,5,6...19].

2) I pick two ID´s, for example number 3 and number 6.

What I need:

1) Generate a vector of size N-1, where the N=5. This vector should not contain number 3 and number 6, only the remaining ID´s, and do not repeat them. For example: new vector = [7,2,19,4]. Yes, only 4 items because the 5th is the number 3 or number 6, they will play with this new created groups, so 1+4 =5(N).

My problem:

1) I need to do this like 1 millions times. It is very slow. I believe that this part of code is the most heavy, because I deleted that part and the program runs really fast without it.

My question:

1) Below is my code, the do while loop, can I somehow optimize it ? maybe I need to use another structure or smarter method to generate this ?

Code:

for (int i = 0; i < _iterations; i++)
    {
        players.clear();
        int y = 0;
        do{
            // _pop_size = 20
            int rand_i = static_cast<int>(rand_double(0, _pop_size));
            if (rand_i != 3 && rand_i 6){
             // verify if the ID already exists in vector
                if (std::find(players.begin(), players.end(), rand_i) == players.end()){
                    players.push_back(rand_i);
                    ++y;
                }
            }
          } while (y < _group_size - 1);
   // ...
   // ...
   // ...
   // ...

rand_double() function:

    double rand_double(int min, int max) const
{
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(min, max);

    return dist(mt);
}




Aucun commentaire:

Enregistrer un commentaire