0

I want a vector that is filled automatically with random letters without repeating any, but whenever I compile the program it generates the same letters in the same positions

this is my code:

string alphabet[27] = { "A","B","C","D","E","F","G","H","I","J","K","L","M","N","Ñ","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
string vector[20];
int pos[20];
int r;
bool rep = false;

int main() {

    cout << "Generate vector" << endl;

    for (int i = 0; i < 20; i++) {

        do {
        rep = false;
        r = rand() % 27;
        vector[i] = alphabet[r];
        pos[i] = r;

                for (int j = 0; j < i; j++) {
                if (r == pos[j])
                    rep= true;
            }
        } while (rep == true);
    }

    for (int i = 0; i < 20; i++) {
        cout << i << " . " << vector[i] << endl;
    }

    _getch();

    return 0;
}
Eduardo Andres
  • 192
  • 1
  • 8
  • 1
    Try std::shuffle instead. http://en.cppreference.com/w/cpp/algorithm/random_shuffle the code becomes a lot simpler. – drescherjm Jan 26 '18 at 20:23
  • 1
    Please read [the documentation on `rand`](http://en.cppreference.com/w/cpp/numeric/random/rand). It explains why this happens. Also consider using C++ constructs like [the one in the example at the bottom](http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution) instead of C functions. – nwp Jan 26 '18 at 20:25
  • Do not use `rand`, it has almost all the drawback one can think of. If your compiler supports C++11, use `random` from Standard C++ library. Or the same from Boost if not. – Daniel Langr Jan 26 '18 at 21:03

0 Answers0