Skip to content

Instantly share code, notes, and snippets.

@bitsmanent
Last active June 19, 2018 17:57
Show Gist options
  • Save bitsmanent/448b84fe1a5425b68df2553da237db3e to your computer and use it in GitHub Desktop.
Save bitsmanent/448b84fe1a5425b68df2553da237db3e to your computer and use it in GitHub Desktop.
Deal with permutations of a given string (with callback)
#include <stdio.h>
#include <string.h>
void swap(char *a, char *b);
void onperm(char *s);
void sperm(char *s, int len, int cur, void (*fn)(char *s));
void
onperm(char *s) {
printf("%s\n", s);
}
void
sperm(char *s, int len, int cur, void (*fn)(char *s)) {
int i;
if(cur == len - 1) {
fn(s);
return;
}
for(i = cur; i < len; ++i) {
swap(s + cur, s + i);
sperm(s, len, cur + 1, fn);
swap(s + cur, s + i);
}
}
void
swap(char *a, char *b) {
char t = *a;
*a = *b;
*b = t;
}
int
main(int argc, char *argv[]) {
if(argc != 2) {
printf("Usage: %s <string>\n", argv[0]);
return 1;
}
sperm(argv[1], strlen(argv[1]), 0, onperm);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment