Problem Description:
N Personal siege One lap, the 1th person from 1 began to count off, counted to M of the people out, and then from the next person began to count off from 1, repeat the game n-1 times, every time the elimination of 1 people, the last remaining person is the winner.
Solid method:
This is the Joseph ring problem, can be implemented with a linked list, I am here with an array implementation, the specific analysis is as follows:
Use variables: Take n=8,m=4 as an example to illustrate
R: Control cycle Times
I: Used to record the person position of each dequeue, change from 1 to 8 and then to 1
J: Used to control the count off, from 1 to 4, in to 1 ....
Figure 1
Figure 2
Figure 3
Figure 4
Figure 5
Figure 6
Figure 7
Figure 8
Note the place:
1) Simulation of the process, starting from 1 to count, up to 4, and starting from 1, so to take the operation of 4, but the range of j%4 from 0~3, the scope of the hope is 1~4, so the correct expression of J is j=j%4+1;
2) The variable i indicates which person is reported by the report, each continued to count should be 8 after the touch plus 1, that is, i=i%8+1;
3) in the process of making a count, to skip the already out of the person, the implementation of the array value is set to its subscript, each row out of a position, the position of the element will be changed to 0, if a position corresponding to the array element value is 0, the change position is skipped. The position where the array element value is not 0 after 7 rounds is winner
#include <stdio.h> #include <stdlib.h>int main () {const int n=8; const int m=4; int a[9]={0,1,2,3,4,5,6,7,8}; int r=1; int i,j; for (i=1,j=1;r<=7;) {while (a[i]==0) i=i%n+1; if (j%m==0) {printf ("a[%d]=%d\n", I,a[i]); a[i]=0; j=0; r++; } i=i%n+1; j=j%m+1; } for (i=0;i<n;i++) {if (a[i+1]!=0) printf ("The last winner is:%d\n", a[i+1]); } return 0;}
"Brush Quiz" with an array of analog Joseph ring