Created
June 19, 2018 17:56
-
-
Save bitsmanent/0cfd9f37eff499e3e2ec3cd8b9a55fda to your computer and use it in GitHub Desktop.
Deal with permutations with repetitions 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 <stdlib.h> | |
#include <string.h> | |
void onperm(char *s, int len); | |
unsigned powu(unsigned base, unsigned exp); | |
int srperm(char *s, int len, void (*fn)(char *, int)); | |
void | |
onperm(char *s, int len) { | |
printf("%s\n", s); | |
} | |
unsigned | |
powu(unsigned base, unsigned exp) { | |
unsigned int r = 1; | |
while(exp > 0) { | |
if(exp & 1) | |
r *= base; | |
base = base * base; | |
exp >>= 1; | |
} | |
return r; | |
} | |
int | |
srperm(char *s, int len, void (*fn)(char *, int)) { | |
unsigned slen = strlen(s); | |
char *gp = calloc(len + 1, sizeof(char)); | |
int total_n = powu(slen, len); | |
int i, j, n; | |
for(i = 0; i < total_n; ++i) { | |
n = i; | |
for(j = 0; j < len; ++j) { | |
gp[len -j -1] = s[n % slen]; | |
n /= slen; | |
} | |
fn(gp, slen); | |
} | |
free(gp); | |
return 0; | |
} | |
int | |
main(int argc, char *argv[]) { | |
if(argc != 2) { | |
printf("Usage: %s <string>\n", argv[0]); | |
return 1; | |
} | |
srperm(argv[1], strlen(argv[1]), onperm); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment