0

I need to generate all the possible combinations of a given char variables in specified length and RETURN the one that matches my criteria.

So, by searching I found the following solution:

#include <bits/stdc++.h> 

void printAllCombinations(char set[], std::string prefix, int sizeofSet, int k) { 

   if (k == 0) { 
       std::cout << (prefix) << std::endl; 
       /*
            If(prefix is matched) {
                 return prefix;
            }
      */ 
       return;   
   } 

   for (int i = 0; i < sizeofSet; i++) { 
       std::string newPrefix; 
       newPrefix = prefix + set[i]; 
       printAllCombinations(set, newPrefix, sizeofSet, k - 1); 
   } 

} 

int main() {             
    char mySet[] = {'a', 'b'}; 
    int lengthOfGeneratedStrings = 2; 
    printAllCombinations(mySet, "", sizeof(mySet), lengthOfGeneratedStrings); 
}

Now, I need to change this void function so I can return the qualified string (prefix) as pointed in the commented part of the code.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Bamshad
  • 115
  • 1
  • 2
  • 10

2 Answers2

1

easily you can do this :

#include <iostream>
#include <string>
std::string returnString(const std::string &input) {
  std::string tmp{input};
  if (tmp == std::string("ghasem")) {
    return tmp;
  } else {
    return std::string("NULL");
  }
}

int main(void) {
  std::cout << returnString("ghasem") << std::endl;
  std::cout << returnString("Another")<< std::endl;
  return 0;
}
$> g++ -o output -std=c++17 main.cpp
$> ./output
ghasem
NULL
$>
Ghasem Ramezani
  • 2,683
  • 1
  • 13
  • 32
0

What you want is std::ostringstream. To use it #include <sstream>. The inputting is exactly like std::cout so you only need to change a few lines.

You shouldn't #include <bits/stdc++.h> > here why >


#include <string>
#include <iostream>
#include <sstream>

std::string getAllCombinations(char set[], std::string prefix, int sizeofSet, int k) {
    std::ostringstream stream;
    if (k == 0) {
        stream << (prefix) << '\n';
        return stream.str();
    }

    for (int i = 0; i < sizeofSet; i++) {
        std::string newPrefix;
        newPrefix = prefix + set[i];
        stream << getAllCombinations(set, newPrefix, sizeofSet, k - 1);
    }
    return stream.str();
}

int main() {
    char mySet[] = { 'a', 'b' };
    int lengthOfGeneratedStrings = 2;
    std::cout << getAllCombinations(mySet, "", sizeof(mySet), lengthOfGeneratedStrings);
}

As you can see, the std::ostringstream is declared and then filled with operator<<. To get the resulting std::string use .str().

Also, don't write << std::endl; - especially in a recursive function. > here why >

Stack Danny
  • 7,754
  • 2
  • 26
  • 55