Skip to content

Instantly share code, notes, and snippets.

@cslarsen
Last active September 5, 2015 07:35
Show Gist options
  • 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´´.
*/
#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;
}
bool uniq(int counts[MAX])
{
for ( int p=0; p<MAX; ++p )
for ( int i=p+1; i<MAX; ++i )
if ( counts[p] == counts[i] )
return false;
return true;
}
int main()
{
int counts[MAX] = {0, 0, 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