vendredi 17 février 2017

Not random random [duplicate]

This question already has an answer here:

I have a function which copies a random element from a vector to result vector. Each time I run it returns a vector with random elements from another vector (it's that I want), but if I run it in a cycle it returns N the same values (result vectors). What can I do to get N random elements in a cycle?

void buildRandomText (map <string, vector <string>> myMap, vector <string> & result, string str) {
    srand( time(0) );
    for (auto it = myMap.begin(); it != myMap.end(); ++it) {
        if (it->first == str) {
            string tmp = it->second[rand() % it->second.size()];
            result.push_back(tmp);
            buildRandomText(myMap, result, tmp);
        }
    }
}

// main:

map <string, vector <string>> myMap;

myMap.insert ( pair<string, vector <string>>("1", {"2", "3", "4" }));
myMap.insert ( pair<string, vector <string>>("2", {"3", "4", "5" }));
myMap.insert ( pair<string, vector <string>>("3", {"4", "5", "6" }));
myMap.insert ( pair<string, vector <string>>("4", {"5", "6", "7" }));

//showMap(myMap);

vector <string> result;

for (int i = 0; i < 3; i++) {
    buildRandomText(myMap, result, "1");
    //showVector(result); here will be random, but the same 3 vectors
    cout << endl;
    result.clear();
}




Aucun commentaire:

Enregistrer un commentaire