Scrambling strings in C++

Does anyone have some code that takes a string (stl string class), and prints out every single combinations of characters for that string? I'm looking for a brute-form algorithm that takes a string and prints out every possible scrambling for it. I need it for a game I am programming in my free time. Code would be nice, thank you.

Like "cat" would print:

atc
tac
tca
....
etc
LVL 2
LinkyAsked:
Who is Participating?
 
jkrCommented:
Sure, use 'next_permutation', e.g.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <functional>
using namespace std ;

int main ()
{

string s = "cat";

    while ( next_permutation(s.begin(), s.end()) )
    {
        cout << s << endl;
    }

return 0;
}
0
 
B1-66ERCommented:
Hi Linky.
And to get another part of permutations you need to use prev_permutation (add next lines in jkr code):

  s = "cat";
  while ( prev_permutation(s.begin(), s.end()) )
  {
    cout << s << endl;
  }
0
 
jkrCommented:
>>And to get another part of permutations you need to use prev_permutation

Why? That loop performs all possible permutations.
0
 
LinkyAuthor Commented:
Thanks for the help guys. I knew STL had something to do it.
0
 
B1-66ERCommented:
Hi jkr.
>> Why? That loop performs all possible permutations.

The loop performs all possible permutations if you pass all symbols in alphabet order ( instead "cat" must be "act"). But if we will pass "cat", then to get all possible permutations, we must make permutation in two ways: next and prev.

So Linky can use only your example but instead "cat" write "act"

string s = "act";

  while ( next_permutation(s.begin(), s.end()) )
  {
    cout << s << endl;
  }
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.