Advertisement
Guest User

7. Hot Potato

a guest
May 28th, 2021
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <list>
  3. #include <string>
  4. #include <sstream>
  5.  
  6. std::list<std::string> readInput(std::string &turns) {
  7.     std::list<std::string> names;
  8.     std::string line;
  9.     getline(std::cin, line);
  10.     std::istringstream istr(line);
  11.     std::string name;
  12.     while (istr >> name) {
  13.         names.push_back(name);
  14.     }
  15.     getline(std::cin, turns);
  16.     return names;
  17. }
  18.  
  19. std::list<std::string>::iterator setItToNextPos(std::list<std::string>& names,
  20.                                                 std::list<std::string>::iterator it) {
  21.     std::list<std::string>::iterator newPos;
  22.     if (std::next(it) == names.end()) {
  23.         newPos = names.begin();
  24.     } else {
  25.         newPos = std::next(it);
  26.     }
  27.     return newPos;
  28. }
  29.  
  30. std::string hotPotato(const int turns, std::list<std::string>& names) {
  31.     int currTurns = turns;
  32.     std::list<std::string>::iterator it = names.begin();
  33.     currTurns--; //by pointing the first is one turn
  34.     std::list<std::string>::iterator removeIt;
  35.     while (names.size() != 1) {
  36.         if (currTurns == 0) {
  37.             removeIt = it;
  38.             it = setItToNextPos(names, it);
  39.             currTurns = turns;
  40.             currTurns--;
  41.             std::cout << "Removed " << *removeIt << std::endl;
  42.             names.remove(*removeIt);
  43.             continue;
  44.         }
  45.         it = setItToNextPos(names, it);
  46.         currTurns--;
  47.     }
  48.     return *it;
  49. }
  50.  
  51. int main()
  52. {
  53.     std::string turnsStr;
  54.     std::list<std::string> names = readInput(turnsStr);
  55.     int turns = stoi(turnsStr);
  56.     std::cout << "Last is " << hotPotato(turns, names);
  57. }
  58.  
  59.  
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement