fork(14) download
  1. #include <algorithm>
  2. #include <cassert>
  3. #include <iostream>
  4. #include <iterator>
  5. #include <random>
  6. #include <vector>
  7.  
  8. // Fisher–Yates_shuffle
  9. std::vector<int> FisherYatesShuffle(std::size_t size, std::size_t max_size, std::mt19937& gen)
  10. {
  11. assert(size < max_size);
  12. std::vector<int> b(size);
  13.  
  14. for(std::size_t i = 0; i != max_size; ++i) {
  15. std::uniform_int_distribution<> dis(0, i);
  16. std::size_t j = dis(gen);
  17. if(j < b.size()) {
  18. if(i < j) {
  19. b[i] = b[j];
  20. }
  21. b[j] = i;
  22. }
  23. }
  24. return b;
  25. }
  26.  
  27. int main()
  28. {
  29. std::random_device rd;
  30. std::mt19937 gen(rd());
  31. std::vector<int> b = FisherYatesShuffle(10, 100, gen);
  32.  
  33. std::copy(b.begin(), b.end(), std::ostream_iterator<int>(std::cout, " "));
  34. return 0;
  35. }
  36.  
Success #stdin #stdout 0s 3476KB
stdin
Standard input is empty
stdout
18 71 10 21 42 15 38 85 80 31