组合问题 之 函数的NULL参数

本文介绍了一种使用C语言实现的方法,用于生成指定函数所有可能的参数组合情况,特别是当部分参数为NULL时的组合。通过两个不同的C语言程序示例展示了如何针对不同数量的参数进行组合生成。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

输出某函数形式 例如 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;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值