1

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

2
  • 4
    Did you check std::shuffle ? Commented Nov 14, 2016 at 7:37
  • 1
    You probably want to check that your shuffle did more than swap the first and last "T". In other words, shuffle until your shuffled word is different from the input. Commented Nov 14, 2016 at 8:20

2 Answers 2

2

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 );
Sign up to request clarification or add additional context in comments.

5 Comments

random_shuffle is deprecated from C++14 and will be removed from C++ 17 dude
Oh Thanks @Danh for the info.
Right idea, though.
en.cppreference.com/w/cpp/algorithm/sample n-combination of n-element set is also a permutation of n-element set.
@khôinguyễn you're free to give your own answer dude
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.