Last active
September 5, 2015 07:35
-
-
Save cslarsen/458043 to your computer and use it in GitHub Desktop.
Permutations in C++
This file contains hidden or 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
/* | |
* Print all permutations of string ``s´´. (C++) | |
* | |
* Solved as a counting problem and coded in a hurry. | |
* | |
* A more elegant and recursive solution: | |
* http://nicolas-lara.blogspot.com/2009/01/permutations.html | |
*/ | |
#include <stdio.h> | |
static const char s[] = "abc"; | |
const int MAX = (sizeof(s)/sizeof(char)) - 1; | |
void print(int counts[MAX]) | |
{ | |
for ( int n=0; n<MAX; ++n ) | |
printf("%c", s[counts[n]]); | |
printf("\n"); | |
} | |
void inc(int counts[MAX], int p = 0) | |
{ | |
if ( p < MAX && ++counts[p] >= MAX ) { | |
counts[p] = 0; | |
inc(counts, p+1); | |
} | |
} | |
bool zero(int counts[MAX]) | |
{ | |
for ( int p=0; p < MAX; ++p ) | |
if ( counts[p] != 0 ) | |
return false; | |
return true; | |
} | |
/* | |
* Are all indices unique? | |
*/ | |
bool uniq(int counts[MAX]) | |
{ | |
int x = 0; | |
for ( int n=0; n<MAX; ++n ) | |
x ^= counts[n] ^ n; | |
return x == 0; | |
} | |
int main() | |
{ | |
int counts[MAX] = {0}; | |
do { | |
if ( uniq(counts) ) | |
print(counts); | |
inc(counts); | |
} while ( !zero(counts) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Made uniq run in O(n) instead of O(n^2).