Last active
June 19, 2018 17:57
-
-
Save bitsmanent/448b84fe1a5425b68df2553da237db3e to your computer and use it in GitHub Desktop.
Deal with permutations of a given string (with callback)
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
#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