Algorithm for Sequence Generator from given String

Please help me writing a C++, Java program to generate sequences from the given string. For example from string str("ABC") we need to generate all possible sequences like "A B C AB AC BC ABC")

Thanks for the help
Who is Participating?
TommySzalapskiConnect With a Mentor Commented:
A recursive solution would probably be the easiest.

string source = "ABC";
int length = source.length();
string current = "";

Generate(source, length, 0, 0,  current,);

Open in new window

//start is where in the source to start, position is where in current we are modifying
void Generate(const string &source, const int length, int start, int position, string &current)
  if(start == length + 1)
    printf("%s\n", current); //or however you do output, just output current
    for(int i = start; i <= length; ++i) //Note: we allow i == length for the \0 to allow A, AB, etc
      current[position] = source[i];
      Generate(source, length, i+1, position+1, current);

Open in new window

Note: This is C++ syntax and assumes order must be maintained. Also, I didn't test it. I mean, I'm not lazy. Any errors are left as an exercise to the student. Yeah.
Do you need the sequences to be generated in that order?
Can we assume that the string will be no longer than, say, 32 characters?
sriramAuthor Commented:
Thanks for the suggestions. I had to modify the program to make it work.
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.