Skip to content

Instantly share code, notes, and snippets.

@pierceh89
Created May 1, 2016 13:01
Show Gist options
  • Save pierceh89/22ec97f698908bd0bcb294938c486087 to your computer and use it in GitHub Desktop.
Save pierceh89/22ec97f698908bd0bcb294938c486087 to your computer and use it in GitHub Desktop.
This code prints out all combinations of given string.
#include <iostream>
using namespace std;
void printAll(const char str[], char buf[], bool used[], int start, int end);
void printAll(const char str[]);
int main(int argc, char* argv[])
{
if(argc != 2)
{
cerr << "Instruction: " << argv[0] << " [string]" << endl;
return -1;
}
printAll(argv[1]);
return 0;
}
void printAll(const char str[])
{
int len = strlen(str);
bool* used = new bool[len];
memset(used, 0, len);
char* buf = new char[len+1];
//strcpy(buf, str);
buf[len] = '\0';
printAll(str, buf, used, 0, len);
free(buf);
free(used);
}
void printAll(const char str[], char buf[], bool used[], int start, int end)
{
if(end - start == 0)
{
// when permutation ends
cout << buf << endl;
return;
}
for(int i=0; i<end; ++i)
{
// if char at i is used, we pass
if(used[i])
continue;
// if char at i is not used yet, put it in the array
used[i] = true;
buf[start] = str[i];
printAll(str, buf, used, start+1, end);
// after it recursively print all permutations set the character is not used
used[i] = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment