/*
*
* 播布客教学视频_C学习笔记_10.1_约瑟夫环问题
* author: syt<sytshanli@163.com>
* create date: 2014.11.29
*
* 1.n个人,分别编号,围城一个环,分别报数,
* 报数过程中报到m则离开,接下来继续从头开始
* 使用特殊到一般的方法(n = 6,m = 3,纸张上分析)
* 2.使用函数实现各个部分(某个操作总是重复进行)
* 3.使用循环解决问题,不确定次数(使用while)
* 4.定义一个变量的时候,什么时候变量会改变呢??
* 5.进行一个打印调试过程
*
*
*
*/
#include<stdio.h>
#define ALL 6 //all people in the ring
#define out 3 //if counter to 3,than out
/* global array for all people in the ring */
int people[ALL];
/*init ring*/
void init_ring(void)
{
int i = 0;
for(i = 0;i < ALL;i++)
people[i] = i +1;
}
/*print ring*/
void print_ring(void)
{
int i = 0;
for(i = 0;i < ALL;i++)
printf("%d ",people[i]);
printf("\n");
}
int main(void)
{
int left; //环中有多少人
int counter;
int i =0;
printf("demo josphus ring problem\n");
init_ring( );
print_ring( );
left = ALL; //left = all people
counter = 0; //counter = 1,2,3
i = 0; //代表从0开始
while(1)
{
/* if(????) */
if(people[i] > 0) //如果这个人没走,那么就要计数,一旦出局了,那么赋值0
counter++; //报数的加法操作(条件呢??)
/* if(????)
一定是有人离开了才会有left减少,
什么情况下会有人离开呢,
*/
if(counter == out) //那就是报到m
{
left--; //什么情况下会少人呢
printf("%d is out\n",people[i]);//谁出局了
print_ring( ); //每次有人出局就打印环
people[i] = 0; //出局后位置为0
counter = 0; //必须重新计数(bug)
}
/*
//调试信息
printf("i = %d ,counter = %d ,left = %d\n",i,counter,left);
print_ring( );
*/
if(left < 1) //什么情况下会推出呢?
break;
i++; //可能数组越界
if(i == ALL)
i = 0;
//getchar( ); //每次回车后才继续
}
printf("问题解决了!");
/*
//init ring
for(i = 0;i < ALL;i++)
people[i] = i +1;
//print ring
for(i = 0;i < ALL;i++)
printf("%d ",people[i]);
printf("\n");
*/
return 0;
}