fork download
  1. #include <random>
  2. #include <vector>
  3. #include <unordered_map>
  4.  
  5. template<class Int, class Generator>
  6. std::vector<Int> randomSample(Int amt, Int lim, Generator& g) {
  7. std::unordered_map<Int, Int> shuffle; // Note: there are much better hash table implementations than std's
  8. for (Int i=1; i<=amt; ++i) {
  9. Int c = std::uniform_int_distribution<Int>(i, lim)(g);
  10. if (!shuffle.count(c))
  11. shuffle[c] = c;
  12. if (!shuffle.count(i))
  13. shuffle[i] = i;
  14. std::swap(shuffle[i], shuffle[c]);
  15. }
  16. std::vector<Int> ans;
  17. for (Int i=1; i<=amt; ++i)
  18. ans.push_back(shuffle[i]);
  19. return ans;
  20. }
  21.  
  22. #include <iostream>
  23. #include <algorithm>
  24.  
  25. int main() {
  26. std::random_device rd;
  27. std::mt19937 gen(rd());
  28. std::vector<int> sample = randomSample(100, 3000, gen);
  29. for (int i=0; i<sample.size(); ++i)
  30. std::cout << sample[i] << ' ';
  31. std::cout << std::endl;
  32. std::sort(sample.begin(), sample.end());
  33. for (int i=0; i<sample.size(); ++i)
  34. std::cout << sample[i] << ' ';
  35. std::cout << std::endl;
  36. }
Success #stdin #stdout 0s 4292KB
stdin
Standard input is empty
stdout
97 1433 833 1224 1499 2643 1984 2411 1905 457 1696 577 2291 1535 459 2199 1403 1046 328 2039 188 483 571 1414 2639 1066 1528 539 2704 2638 782 1879 458 2578 1028 1889 1278 525 2495 884 291 2444 2375 2838 2347 1794 809 2861 1594 1496 50 1963 39 2774 2258 1477 431 90 1681 1430 2884 1547 686 2615 1296 1856 2598 2753 229 1977 2621 480 806 1552 2323 1268 655 1277 629 1129 1015 1949 2819 2984 2569 2238 2672 32 2719 2317 842 138 1121 2840 841 2474 1257 647 1821 526 
32 39 50 90 97 138 188 229 291 328 431 457 458 459 480 483 525 526 539 571 577 629 647 655 686 782 806 809 833 841 842 884 1015 1028 1046 1066 1121 1129 1224 1257 1268 1277 1278 1296 1403 1414 1430 1433 1477 1496 1499 1528 1535 1547 1552 1594 1681 1696 1794 1821 1856 1879 1889 1905 1949 1963 1977 1984 2039 2199 2238 2258 2291 2317 2323 2347 2375 2411 2444 2474 2495 2569 2578 2598 2615 2621 2638 2639 2643 2672 2704 2719 2753 2774 2819 2838 2840 2861 2884 2984