Skip to content

Instantly share code, notes, and snippets.

@ducss2015
Last active August 29, 2015 14:27
Show Gist options
  • Save ducss2015/b6b5c703ea58c5d51d11 to your computer and use it in GitHub Desktop.
Save ducss2015/b6b5c703ea58c5d51d11 to your computer and use it in GitHub Desktop.
Print string combination without using recursion
void PrintCombination(const std::string& str, const std::vector<size_t>& combination) {
for (size_t i = 0; i < combination.size(); ++i) {
std::cout << str[combination[i]];
}
std::cout << std::endl;
}
void PrintCombinationFixedLength(const std::string& str, size_t combination_length) {
std::vector<size_t> combination;
size_t string_length = str.length();
/* initialize */
combination.push_back(0);
while (!combination.empty()) {
// Initialize if needed
while (combination.size() < combination_length) {
combination.push_back(combination.back() + 1);
}
PrintCombination(str, combination);
// Increase the combination by one
while (!combination.empty()) {
++combination.back();
if (combination.back() > string_length - 1 - (combination_length - combination.size()))
combination.pop_back();
else
break;
}
}
}
void PrintCombination(const std::string& str) {
for (size_t i = 1; i <= str.length(); ++i) {
PrintCombinationFixedLength(str, i);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment