Problem Description:
In the Josephus problem primary (using arrays), we present a simple and straightforward solution.
However, after careful review of the code, it was found that the efficiency of such a scheme is not high, specifically, when someone is out, the traversal of the array still needs to be judged,
This is undoubtedly a futile effort, reducing the efficiency of the Code, especially in the number of people.
Solution:
When someone is out, consider placing the next person (not out) of the person who is currently out of the current one (not out) as the next person who is currently out. This ensures that each increase in counter is valid and that the person who has traversed is not yet out. Greatly improve the efficiency of the program. This actually uses the idea of a linked list.
Code:
#include < Stdio.h>/*total People number*/#define ALL 100/*people leave when count to left_counter*/#define Left_counter 3/*next A Rray record the next people ' s Position*/int next[all];/*init next array*/void initnext () {int i = 0; for (i = 0; i < all ; i++) {Next[i] = (i+1)% All;}} /*print next Array*/void Printnext () {int i = 0;for (i = 0; i < all; i++) {printf ("%d", Next[i]);} printf ("\ n");} int main (void) {initnext (); int left = All;/*init Total left number*/int counter = 0;/*init Counter*/int i = 0;/*init array Index*/int prev = All-1; /*init Prev*/while (Left > 0) {counter++;/*if counter = = Left_counter, people out, set next[prev] = next[i] Counter = 0 left--**/if (counter = = Left_counter) {left--;p rintf ("%d is out\n", i+1); counter = 0;next[prev] = next[i];p rintnext ();} /*change prev, Increase index*/prev = I;i = Next[i];} printf ("Problem finished!\n"); return 0;}
Josephus problem Intermediate (use array to simulate linked list, improve efficiency)