Created
May 1, 2016 13:01
-
-
Save pierceh89/22ec97f698908bd0bcb294938c486087 to your computer and use it in GitHub Desktop.
This code prints out all combinations of given string.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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