题目:
输出某函数形式 例如 Fun(str1,str2,str3...)
输出其参数为NULL的各种情形
sample: input Add(tom,lily,andrew)
output :
Add(tom,lily,NULL)
Add(tom,NULL,andrew)
Add(NULL,lily,andrew)
Add(tom,NULL,NULL)
Add(NULL,lily,NULL)
Add(NULL,NULL,NULL)
纯C语言代码:
#include <string.h>
#include <stdio.h>
#define N 100
int a[N]={0},end=0;
void out(const char *buf)
{
const char *pbuf = buf;
char *pstart = strstr(buf,"(");
char *pend = strstr(buf,")");
while(pbuf<=pstart) //起头
{
printf("%c",*pbuf);
pbuf++;
}
for(int i=1;i<N;i++) //每一次排列完成 a[0]-a[1]-a[2]...都是原样输出的
{
if(a[i]<=a[i-1]) //收尾
{
while(pbuf!=pend) //输出a[i-1]到末尾的数
{
printf("%c",*pbuf);
pbuf++;
}
printf(")\n");
return;
}
for(int j=a[i-1]+1;j<a[i]; )
{
printf("%c",*pbuf);
if(*pbuf==',')
{
j++;
pbuf++;
continue;
}
pbuf++;
}
printf("NULL"); //替换
if (strstr(pbuf,",")) //指向下一个参数 第a[i]+1个
{
pbuf = strstr(pbuf,",");
pbuf++;
printf(",");
}
else //后面没有参数了,收尾
{
printf(")\n");
return;
}
}
}
void comb(int m,int k,const char *buf)//从m个元素中取出k个元素的组合//换成全部输出
{
int i,j;
for(i=m;i>=k;i--)
{
a[k]=i;
if(k>1)
comb(i-1,k-1,buf);
else
{
for(j=1;j<=end;j++)
{
printf("%d ",a[j]);
}
printf("\n");
out(buf);
printf("\n");
}
}
}
int main()
{
char *str="Test(a,b,544,esd)";
char *pstr=str;
int n=1;
while(*pstr)
if(*pstr++==',')
n++;
for (int i=1;i<=n;i++)
{
end=i;
comb(n,i,str);
}
return 0;
}
#include <stdio.h>
unsigned int g_flag=0;
int TOTAL=5;
void printflag_()
{
for(int x=TOTAL-1;x>=0;x--)
printf("%d",((g_flag>>x)&1));
};
void comb_(int total,int part)
{
for(int i=total;i>=part;i--)
{
g_flag |= 1<<(i-1); //该位置标记1
for (int x=0;x<total-i;x++) //该位置以前到该递归起始位置 标记0;
g_flag &= ~(1<<(total-x-1));
for (int y=1;y<i;y++) //该位置以后全部标记0;
g_flag &= (-1)<<y;
if ( part>1 )
{
comb_(i-1,part-1);
}
else
{
printflag_();
printf("\n");
}
}
};
void comb(int total,int part)
{
TOTAL=total;
comb_(total,part);
}
int main()
{
comb(5,2);
printf("\n");
comb(6,2);
return 0;
}