fork download
  1. #include <algorithm>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <random>
  5. #include <vector>
  6.  
  7.  
  8. template <typename T, typename Rnd>
  9. class Deck
  10. {
  11. public:
  12. Deck(const std::vector<T>& cards, Rnd& rnd) : cards(cards), rnd(rnd)
  13. {
  14. shuffle();
  15. }
  16.  
  17. T draw() {
  18. ++index;
  19. if (index == cards.size())
  20. {
  21. shuffle();
  22. index = 0;
  23. }
  24. return cards[index];
  25. }
  26. private:
  27. void shuffle()
  28. {
  29. std::cout << "shuffle\n";
  30. std::shuffle(this->cards.begin(), this->cards.end(), rnd);
  31. }
  32.  
  33. private:
  34. std::vector<T> cards;
  35. std::size_t index = -1;
  36. Rnd& rnd;
  37. };
  38.  
  39.  
  40. int main()
  41. {
  42. unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  43. std::mt19937 rnd(seed);
  44. Deck<int, std::mt19937> deck({1, 1, 2, 2, 3, 3, 4, 4, 0, 5}, rnd);
  45.  
  46.  
  47. for (int i = 0; i != 42; ++i) {
  48. std::cout << deck.draw() << std::endl;
  49. }
  50. }
  51.  
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
shuffle
1
3
4
4
1
2
3
0
2
5
shuffle
2
0
5
3
3
4
1
1
4
2
shuffle
4
0
3
2
1
5
2
3
4
1
shuffle
3
4
4
1
5
0
2
3
2
1
shuffle
3
0