这个是《C 专家编程》P278的第一题,下面是我写的C语言解答。 (MinGW/ gcc v4.8.1 -std=c11)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char **npr(char **, char);
int fac(int);
int main(int argc, char *argv[]){
if(argc>1){
char *str = argv[1];
int len = strlen(str);
char *init_arr = malloc(2);
*init_arr = str[0];
*(init_arr+1) = '\0';
char **arr = &init_arr;
int n=1;
while(n<len){//迭代
arr = npr(arr, *(str+n));
n++;
}
for(int i=0;i<fac(len);i++)printf("%%%s\n",arr[i]);
// 打印
}
return 0;
}
char **npr(char **arr, char c){//B版选修2-3排列公式
int len0 = strlen(*arr);
int len1 = len0+1;
int npr0 = fac(len0);
int npr1 = fac(len1);
char **strarrp = malloc(sizeof(char**)*npr1);
for(int i=0;i<npr1;i++)strarrp[i]=malloc(strlen(*arr)+2);
for(int i=0;i<npr0;i++){
for(int j=0;j<len1;j++){
char *curr = strarrp[i*len1+j];
strcpy(curr,arr[i]);
int k=len0;
while(k>j){
*(curr+k) = *(curr+k-1);
k--;
}
*(curr+j) = c;//插入
*(curr+len1) = '\0';
}
}
free(arr);
return strarrp;
}
int fac(int n){
switch(n){
case 0: return 1;
case 1: return 1;
default: return n*fac(n-1);
}
}