Advertisement
Taraxacum

Josephus Problem

Nov 15th, 2018 (edited)
382
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.18 KB | None | 0 0
  1. /**
  2.  * People are standing in a circle waiting to be executed. Counting begins at
  3.  * a specified point in the circle and proceeds around the circle in a
  4.  * specified direction. After a specified number of people are skipped, the
  5.  * next person is executed. The procedure is repeated with the remaining
  6.  * people, starting with the next person, going in the same direction and
  7.  * skipping the same number of people, until only one person remains, and
  8.  * is freed.
  9.  *
  10.  * The problem — given the number of people, starting point, direction, and
  11.  * number to be skipped — is to choose the position in the initial circle to
  12.  * avoid execution.
  13.  *
  14.  * https://en.wikipedia.org/wiki/Josephus_problem
  15. */
  16.  
  17. #include <iostream>
  18.  
  19. unsigned josephus1(const unsigned cnt, const unsigned start, const unsigned step)
  20. {
  21.     bool* dead = new bool[cnt] { false };
  22.  
  23.     unsigned exec_cnt = 0;
  24.     unsigned step_cnt = 0;
  25.  
  26.     unsigned i;
  27.     for (i = start % cnt; exec_cnt < cnt; i = (i + 1) % cnt) {
  28.         if (!dead[i]) {
  29.             step_cnt++;
  30.             if (step_cnt == step) {
  31.                 dead[i] = true;
  32.  
  33.                 std::cout << i << " ";
  34.  
  35.                 exec_cnt++;
  36.                 step_cnt = 0;
  37.             }
  38.         }
  39.     }
  40.  
  41.     std::cout << std::endl;
  42.  
  43.     delete[] dead;
  44.  
  45.     return (i - 1) % cnt;
  46. }
  47.  
  48. unsigned josephus2(const unsigned cnt, const unsigned start, const unsigned step)
  49. {
  50.     unsigned* next = new unsigned[cnt];
  51.  
  52.     for (size_t i = 0; i < cnt; i++) {
  53.         next[i] = (i + 1) % cnt;
  54.     }
  55.  
  56.     unsigned counter = 0;
  57.     unsigned last = 0;
  58.  
  59.     unsigned i;
  60.     for (i = start % cnt; next[i] != i; i = next[i]) {
  61.         counter++;
  62.  
  63.         if (counter == step) {
  64.             std::cout << i << " ";
  65.             next[last] = next[i];
  66.             counter = 0;
  67.         } else {
  68.             last = i;
  69.         }
  70.     }
  71.  
  72.     std::cout << i << std::endl;
  73.  
  74.     delete[] next;
  75.  
  76.     return i;
  77. }
  78.  
  79. int main(int argc, char const* argv[])
  80. {
  81.     unsigned ans = josephus1(10, 0, 3);
  82.     std::cout << "The last one is " << ans << std::endl;
  83.  
  84.     ans = josephus2(10, 0, 3);
  85.     std::cout << "The last one is " << ans << std::endl;
  86.  
  87.     return 0;
  88. }
  89.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement