josephus Problem 初级(使用数组)

问题描述:

这是一个很经典的问题,一桌人一起吃饭,比如有6个人,第一个人从1开始报数,后面的人报的数依次递增,当报出的数为某一个数时,报数的那个人出局,游戏继续。出局的那个人后面的还没有出局的人继续从1开始报数,直到所有的人出局为止。得出出局顺序。

比如有6个人,分别为1,2,3,4,5,6 。报数到3的人出局,则出局顺序应该是:3,6, 4, 2, 5, 1

解决方案:

可以采取对数组置标志位解决,将其置为0表示已出局,则遍历到它的时候,不需要增加计数。置标志位在实际开发中也是比较常见的一种思路。

代码:

#include <stdio.h>
/*total people number*/
#define ALL 100	
/*people leave when count to left_counter*/
#define left_counter 3
/*people array*/
int people[ALL];

/*init people array*/
void initPeople()
{
	int i = 0 ;
	for (i = 0; i < ALL; i++)
	{
		people[i] = i+1;
	}
}

/*print people array*/
void printPeople()
{
	int i = 0;
	for (i = 0; i < ALL; i++)
	{
		printf("%d ",people[i]);
	}
	printf("\n");
}

int main(void)
{
	initPeople();
	int left = ALL;		/*init total left number*/
	int counter = 0;	/*init counter*/
	int i = 0;		/*init array index*/
	while (1)
	{
		if (0 != people[i])
		{
			counter++;
		}
		/*if counter == left_counter , peopler out, set people[i] = 0
 		  counter = 0; 
		  left--;
		**/
		if (counter == left_counter)
		{
			left--;
			printf("%d is out\n", people[i]);
			counter = 0;
			people[i] = 0;
			printPeople();
		}		
		/*if no people left, problem solved*/
		if (0 == left)
		{
			printf("problem finished!\n");
			break;
		}
		/*increase index*/
		i++;
		if (i == ALL)
		{
			i = 0;
		}	
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值