Darius Brown
Darius Brown

Reputation: 35

Print out each character randomly

I am creating a small game where the user will have hints(Characters of a string) to guess the word of a string. I have the code to see each individual character of the string, but is it possible that I can see those characters printed out randomly?

string str("TEST");
for (int i = 0; i < str.size(); i++){
cout <<" "<< str[i];

output:T E S T desired sample output: E T S T

Upvotes: 1

Views: 135

Answers (2)

Monik Sidhpura
Monik Sidhpura

Reputation: 1

Use the following code to generate the letters randomly.

    const int stl = str.size();
    int stl2 = stl;
    while (stl2 >= 0)
    {
        int r = rand() % stl;
        if (str[r] != '0')
        {
            cout<<" "<<str[r];
            str[r] = '0';
            stl2--;
        }
    }

This code basically generates the random number based on the size of the String and then prints the character placed at that particular position of the string. To avoid the reprinting of already printed character, I have converted the character printed to "0", so next time same position number is generated, it will check if the character is "0" or not.

If you need to preserve the original string, then you may copy the string to another variable and use it in the code.

Note: It is assumed that string will contain only alphabetic characters and so to prevent repetition, "0" is used. If your string may contain numbers, you may use a different character for comparison purpose

Upvotes: 0

Saurav Sahu
Saurav Sahu

Reputation: 13934

Use random_shuffle on the string:

random_shuffle(str.begin(), str.end());

Edits: C++11 onwards use:

auto engine = std::default_random_engine{};
shuffle ( begin(str), end(str), engine );

Upvotes: 2

Related Questions