Skip to content

Instantly share code, notes, and snippets.

@bl0ckeduser
Created June 26, 2012 22:18
Show Gist options
  • Save bl0ckeduser/2999696 to your computer and use it in GitHub Desktop.
Save bl0ckeduser/2999696 to your computer and use it in GitHub Desktop.
String permutations
/*
* Print all permutations of a string,
* using a tree-recursive routine. I
* bet there are smart algorithms out
* there that beat this. I did not look
* up an algorithm when writing this.
*
* Bl0ckeduser
* June 26, 2012
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 16
void fail(char* s){
puts(s); exit(1);
}
void permut(int n, char avail[], char prev[])
{
int i, j;
char child_avail[N];
char chars[N];
/* go through all available characters */
for(i = 0; avail[i]; i++)
if(avail[i] != '!') {
/* found an available character;
cross it out from the child's
available characters list */
strcpy(child_avail, avail);
child_avail[i] = '!';
/* add the character to this
permutation-string */
strcpy(chars, prev);
strncat(chars, &avail[i], 1);
/* print out permutation-string
if a leaf is reached; otherwise,
spawn child */
if(n == 1)
puts(chars);
else
permut(n - 1, child_avail, chars);
}
}
int main(int argc, char** argv)
{
char set[N];
if(scanf("%s", set) == EOF)
fail("failed to input string");
if(strlen(set) > N)
fail("string bigger than hardcoded limit");
if(strstr(set, "!"))
fail("! is used internally");
permut(strlen(set), set, "");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment