33,008
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
int factorial(int n);
void emernuation(char** des, char* src);
int nWidth(int n);
int main(int argc, char* argv[]){
int i;
char *strPattern;
int nPattern;
char **strDes;
int nDes;
int nPrintWidth;
//strPattern = "abc";
strPattern = argv[1];
nPattern = strlen( strPattern );
nDes = factorial( nPattern );
//memory allocation
strDes = (char **)malloc(sizeof(char*) * nDes);
assert(strDes);
for(i=0; i<nDes; i++){
strDes[i] = (char *)malloc(sizeof(char) * (1+nPattern));
assert(strDes[i]);
strDes[i][0] = '\0';
}
//address: send the strPattern to a function and get the result in the strDes
emernuation(strDes, strPattern);
//print the result
nPrintWidth = nWidth(factorial(nPattern));
for(i=0; i<nDes; i++){
fprintf(stdout, "%0*d %s\n",nPrintWidth, i+1, strDes[i]);
}
//free memory
for(i=0; i<nDes; i++){
if(strDes[i]){
free(strDes[i]);
}
}
if(strDes){
free(strDes);
}
return 0;
}
int nWidth(int n){
int ans;
ans = 1;
while(n/10!=0){
ans++;
n=n/10;
}
return ans;
}
int factorial(int n){
assert(n >= 0);
if(0 == n || 1 == n){
return 1;
}
else{
return n * factorial( n-1 );
}
}
void emernuation(char** des, char* src){
int h,i,j,k;
int nSection;
int nSrc;
char **strDes;
char *strSrc;
char **strSub;
char ***pStrSection;
strDes = des;
strSrc = src;
nSrc = strlen(strSrc);
nSection = factorial(nSrc-1);
//exit
if(nSrc < 2){
for(j=0;;j++){
if(strDes[0][j] == '\0'){
strDes[0][j] = strSrc[0];
strDes[0][j+1] = '\0';
break;
}
}
return ;
}
//memory allocation
strSub = (char **)malloc(sizeof(char *) * nSrc);
assert(strSub);
for(j=0;j<nSrc;j++){
strSub[j] = (char *)malloc(sizeof(char) * nSrc);
assert(strSub[j]);
}
pStrSection = (char ***)malloc(sizeof(char **) * nSrc);
assert(pStrSection);
//address
for(h=0;h<nSrc;h++){
//sub strings
for(i=0,j=0;j<nSrc;j++){
if(j!=h){
strSub[h][i] = strSrc[j];
i++;
}
}
strSub[h][i] = '\0';
//sub address
pStrSection[h] = strDes + h * nSection;
//copy the current character scanned
for(i=0;i<nSection;i++){
//strconchar( pStrSection[h][i], strSrc[h]);
for(j=0;;j++){
if(pStrSection[h][i][j] == '\0'){
pStrSection[h][i][j] = strSrc[h];
pStrSection[h][i][j+1] = '\0';
break;
}
}
}
//recursion to address the sub strings
emernuation(pStrSection[h], strSub[h]);
}
//memory unallocation
for(j=0;j<nSrc;j++){
if(strSub[j]){
free(strSub[j]);
}
}
if(strSub){
free(strSub);
}
if(pStrSection){
free(pStrSection);
}
return;
}