Advertisement
bartekltg

Josephus

Nov 3rd, 2015
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3.  
  4. int survivor(int circle_size, int kill )
  5. {
  6.     if (circle_size ==1 ) return 1;
  7.     int s= survivor(circle_size-1, kill) + kill;
  8.     s = (s-1)%circle_size +1; //wrapping around circle (1,2...circle_size)
  9.     return s;
  10. }
  11.  
  12.  
  13. int i_th_last_survivor(int circle_size, int kill, int n_surv, int who)
  14. {
  15.     if (circle_size == n_surv ) return who;
  16.     int s= i_th_last_survivor(circle_size-1, kill, n_surv, who) + kill;
  17.     s = (s-1)%circle_size +1; //wrapping around circle (1,2...circle_size)
  18.     return s;
  19. }
  20.  
  21.  
  22. void simulation(int circle_size, int kill, int n_show)
  23. {
  24.     int people[circle_size];
  25.     int last_circle_size = circle_size;
  26.     int i;
  27.  
  28.     for (i=0;i<circle_size;i++)
  29.         people[i]=i+1;
  30.  
  31.     int read=0, write=0;
  32.     int counter=1;
  33.     while (circle_size>0)
  34.     {
  35.         if ((counter++)%kill==0){
  36.             if (circle_size<=n_show)
  37.                 printf("%d indicated as %dth from the end\n",people[read],circle_size);
  38.             read++;
  39.             circle_size--;
  40.  
  41.         }else
  42.             people[write++]=people[read++];
  43.         if (read>=last_circle_size ){
  44.             read=0;
  45.             write=0;
  46.             last_circle_size  = circle_size;
  47.         }
  48.     }
  49. }
  50.  
  51.  
  52.  
  53.  
  54. int main(void)
  55. {
  56.     printf("Flavius: %d\n",survivor(41,3));
  57.     printf("Hungry Lu: %d\n",survivor(100,5));
  58.     printf("Flavius and his friend: %d %d\n\n",i_th_last_survivor(41,3,2,1),i_th_last_survivor(41,3,2,2));
  59.     printf("Flavius:\n");
  60.     simulation(41,3,4);
  61.     printf("Monks:\n");
  62.     simulation(100,5,4);
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement