main.cpp 1.3 KB

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