Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Last active September 5, 2015 07:35
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cslarsen/458043 to your computer and use it in GitHub Desktop.
Save cslarsen/458043 to your computer and use it in GitHub Desktop.
Permutations in C++
/*
* 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) );
}
@cslarsen
Copy link
Author

cslarsen commented Dec 8, 2014

Made uniq run in O(n) instead of O(n^2).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment