Advertisement
alfps

Random unique numbers

Dec 30th, 2020
947
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. #include <random>
  2. using   std::random_device, std::uniform_real_distribution;     // <random>
  3.  
  4. auto seed() -> auto { return random_device()(); }
  5.  
  6. template< class URBG, class Func >
  7. void choose_randomly( const int n_values, const int range_size, URBG& bits, const Func& f )
  8. {
  9.     uniform_real_distribution<double> random_from;
  10.  
  11.     int n_generated = 0;
  12.     for ( int value = 0; value < range_size; ++value ) {
  13.         const int n_to_generate = n_values - n_generated;
  14.         const int n_remaining_values = range_size - value;
  15.         if( random_from( bits ) <= 1.0*n_to_generate/n_remaining_values ) {
  16.             f( value );  ++n_generated;
  17.             if( n_generated == n_values ) {
  18.                 return;
  19.             }
  20.         }
  21.     }
  22. }
  23.  
  24. #include <algorithm>
  25. #include <iostream>
  26. #include <vector>
  27. using   std::shuffle,               // <algorithm>
  28.         std::cout, std::endl,       // <iostream>
  29.         std::vector;                // <vector>
  30.  
  31. auto main() -> int
  32. {
  33.     auto bits = std::mt19937( seed() );     //Standard mersenne_twister_engine.
  34.  
  35.     vector<int> key;
  36.     const int n_key_items = 6;
  37.  
  38.     // Linear time generation of 6 random unique digits in sorted order.
  39.     choose_randomly( n_key_items, 10, bits, [&key]( const int digit )
  40.     {
  41.         key.push_back( digit );
  42.     } );
  43.    
  44.     // Linear time shuffling of the result sequence.
  45.     shuffle( begin( key ), end( key ), bits );
  46.  
  47.     // Display it.
  48.     for( const int v: key ) { cout << v << " "; }
  49.     cout << endl;
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement