Description of the problem:
In the Josephus Problem 0 Foundation (using arrays). We propose one of the simplest and most straightforward solutions.
But after a careful look at the code. It is not efficient to find such a scheme, the details are now. When someone is out, traversing the array still needs to be inferred,
This is undoubtedly a futile effort. Reduced code efficiency. is especially evident in the number of people.
How to resolve:
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 addition to the counter is valid. The people who have traversed are not yet out of the game. 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)