Problem Description:
This is a very classic problem, a table of people to eat together, for example, there are 6 people, the first person from 1, the number of people reported in turn, and when the number of reported for a certain number, count the person out, the game continues. Those who have not yet been out of the exit continue to count back from 1 until all the people have been out. Draw out the order of exit.
For example, there are 6 people, respectively, 1,2,3,4,5,6. When a person is out of the 3, the exit order should be: 3, 6, 4, 2, 5, 1
Solution:
You can take a logarithmic set of flag bits to resolve and set it to 0 to indicate that it is out, and you do not need to increment the count when traversing to it. It is also a common way of thinking in the actual development of the place sign.
Code:
#include <stdio.h>/*total People number*/#define ALL/*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;
}