code.cpp 1.1 KB

12345678910111213141516171819202122232425262728293031
  1. /* A group of n prisoners stand in a circle awaiting execution.
  2. * Starting from an arbitrary position(0), the executioner kills
  3. * every kth person until one person remains standing, who is then granted
  4. * freedom (see examples).
  5. * Create a function that takes 2 arguments — the number of people to
  6. * be executed n, and the step size k, and returns the original position
  7. * (index) of the person who survives.
  8. */
  9. #include <numeric>;
  10. int whoGoesFree(int n, int k) {
  11. // create an index of positions
  12. std::vector<int> indexP(n) ;
  13. std::iota (std::begin(indexP), std::end(indexP), 0);
  14. // position of last person killed; c is count to k;
  15. int lastkill = 0, c = 0, target = 0;
  16. // kill everybody
  17. while(n){
  18. // if killing, kill and advance target
  19. if(++c == k){
  20. lastkill = indexP[target];
  21. // this advances the target
  22. indexP.erase(indexP.begin() + target);
  23. c = 0;
  24. n--;
  25. }
  26. // advance the target
  27. else{// determine who might get killed next
  28. target = ++target % indexP.size();}
  29. }
  30. return lastkill;
  31. }